Home > Net >  Search element in binary search tree
Search element in binary search tree

Time:11-05

struct node {
    int data;
    struct node *left; /* left tree part */
    struct node *right; /* right tree part */
};

bool search(struct node *root, int element) {
    
    if ( root -> data == element) {
        return true;
    }

    if (root->data < element) {
        search (root->right, element);
    }
    if (root->data > element) {
        search(root->left, element);
    }
    return false;

}

I want this program to return true if the given element is found in the binary search tree. Otherwise returns false. What's the problem for this recursive progress?

CodePudding user response:

What's the problem for this recursive progress?

As mentioned in the comments, you aren't doing anything with the result of the recursive calls in this function. You want to return them like this:

if (root->data < element) {
    return search(root->right, element);
}
if (root->data > element) {
    return search(root->left, element);
}

Once you've reached the condition to terminate recursive calls, then you will see if the element was found or not.

bool search(struct node *root, int element) {

    // element is not found
    if(!root) return false;
    
    // element is found
    if (root->data == element) {
        return true; // terminate recursive calls
    }

    if (root->data < element) {
        return search(root->right, element);
    }
    if (root->data > element) {
        return search(root->left, element);
    }

}

Edit: Be careful, unlike me, and be sure to check if root is null ;)

  • Related