0

I'm trying to write code that takes a binary search tree and returns the max value within the struct.

However, when I compile with the test files below, I'm getting segmentation faults, and I can't figure out why. Any help would be appreciated. Thank you.

My code:

        int helper_get_max(BTnode_t *root){          //helper function 
            int a = root->value;
            int b = helper_get_max(root->left);
            int c = helper_get_max(root->right);
            if (b>a){
                a = b;
            }
            if(c>a){
                a = c;
            return a;
            }
        }


        int get_max(BST_t* tree){
          if(tree->root==NULL)
            return -1;
          int a = helper_get_max(tree->root);
          return a;
        }

Test code it's supposed to work with:

        bool test_q2a()  {
          BST_t *bst = create_BST();
          BST_insert(bst, 125);

          if (get_max(bst) == 125)  {
            printf("AC\n");
            return true;
          }
          else  {
            printf("WA\n");
            return false;
          }
        }

        int main()  {
          test_q2a();

          return 0;
        }

As stated above, when ran with this test, it gives a segmentation error.

  • What happens when any `->left` (or right) pointer is `NULL`? Unless the tree is infinite in size, there will be some NULLs in there for sure. –  Dec 03 '20 at 14:30
  • And as this is a manageably small program, this is relevant: https://stackoverflow.com/q/25385173/14215102 –  Dec 03 '20 at 14:36
  • If it is really a binary search tree, the nodes should be sorted by value, so you shouldn't need to descend both branches. The maximum value should be found by following all the `right` links or all the `left` links, depending on how you order the nodes in the tree. – Ian Abbott Dec 03 '20 at 14:54
  • this was a homework assignment. It is impossible to run test_q2a() because create_BST() does not appear here – Igor Shinkar Dec 12 '20 at 19:45

0 Answers0