简体   繁体   中英

Recursive boolean function for a binary search tree

I have a class implementing binary search tree and one of my private methods is method bool find(Node<Key, Info> * &node, Key _key); , where node stands for a pointer to a node, we start searching from and _key stands for a unique for every node key. My method is implemented as follows:

template<typename Key, typename Info>
bool BST<Key, Info>::find(Node<Key, Info>* &node, Key _key)
{
    if (node)
    {
        if (node->key == _key)
        {
            return true;
        }
        else
        {
            find(node->left, _key);
            find(node->right, _key);
            return false;
        }
    }
    else return false;
}

And it doesn't return true, even if the element with the given key exists. I added a printing command just before return statement and it executes so my function seems to find the given node, but I guess my understanding is wrong and it still somehow returns false.


Solved

The solution to my problem seems to be found :)

template<typename Key, typename Info>
bool BST<Key, Info>::find(Node<Key, Info>* &node, Key _key)
{
    if (node)
    {
        if (node->key == _key)
        {
            return true;
        }
        else if(_key<node->key)
            return find(node->left, _key);
        else 
            return find(node->right, _key);
    }
    else return false;
}

For binary search trees, you, of course, want to walk down the tree until you find the value or reach nullptr. I'll write out a search function real quick here:

bool search(Node * node, int value){
    if(node == nullptr) //If it's nullptr, we've reached the end without finding value.
        return false;
    if(node->value == value) //If it's value, we've found it!
        return true;
    if(node->value > value) //If value is less than node's value, go to left.
        return search(node->left, value);
    if(node->value < value) //If value is greater than node's value, go to right.
        return search(node->right, value);
}

This is a recursive search for an organized tree (without using templates, for the sake of simplicity). Therefore, in a binary search tree, you first need to check if node is nullptr , then if it is value , and then go from there.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM