-3
bool search(double x, TreeNode *t)
{
    if (t->value == x)
        return true;
    else if (x < t->value)
        search(x, t->left);
    else if (x > t->value)
        search(x, t->right);
    return false;

bool search(double num)
{
    TreeNode *ptr = root;
    return search(num, ptr);
}

The search function with 2 arguments is a private member function of a binary tree class that uses recursion to search for a value. The other search function is called to call the recursive function. This code does not work. I have displayed the value of the recursive function and it does not return 0 or 1. I have no idea why. Also, if I send in a value that is not in the tree, the program crashes so I get no errors to help me.

1 Answers1

1

Your recursion never stops if you don't find an element.
If it's found in the root, you return true.
If it's found somewhere else, you return false.

You need to

  1. Handle the empty tree, and
  2. Return something meaningful when recursing.

Like

bool search(double x, const TreeNode *t)
{
    if (t == nullptr)
        return false;
    else if (t->value == x)
        return true;
    else if (x < t->value)
        return search(x, t->left);
    else
        return search(x, t->right);
}

or

bool search(double x, const TreeNode *t)
{
    return t != nullptr
          && (  t->value == x
            || (t->value < x && search(x, t->left))
            || (t->value > x && search(x, t->right)));
}
molbdnilo
  • 64,751
  • 3
  • 43
  • 82