I am writing a binary search tree and this function called Search takes a value x and searches the nodes in the tree and returns whether it is a leaf or not.

bool search(Node<T>* &currentNode, const T& x) const
{
    //~ cout << "CURRENT NODE DATA: " << currentNode->data << "   :   ";


    /*  FUNCTION: Searches for variable that is passed in X and checks if this value is a leaf or not */

    //Left Subtree Search
    if (x < binTree<T>::root->data)
    {
    if ((leaf(currentNode)) == true)
        { 
          return true;
        }
    else 
    {
    search(currentNode->left, x);   
    }

    }


//Right Subtree Search
else if (x >= binTree<T>::root->data)
{
    //If node in right subtree is a node check 
    if ((leaf(currentNode)) == true)
    {
        return true;
    }   

    else 
    {
    search(currentNode->right, x);
    }

}


 //Return false if the node is not a leaf
 return false;

}  //END OF SEARCH FUNCTION


bool leaf(Node<T>* currentNode) const 
{
    return ((currentNode->left == nullptr && currentNode->right == nullptr) ? true : false);        
}

The seg fault occurs when I recursively call the search function with new updated node. The binary tree is initialized with 100 values and it starts searching at the root.

有帮助吗?

解决方案

This code

if (x < binTree<T>::root->data)

is checking against root, note currentNode, so the test will never change. So if your x value is less than root->data you will keep trying to recurse through currentNode->left until you either hit a leaf (if you are lucky) or you hit a node with a NULL left pointer, in which case you will recurse with currentNode as NULL, which will cause a segfault in leaf when it tries to check for currentNode->left

You should be checking against currentNode. You should also be returning the return value of your search recursive calls

其他提示

You have to declare
bool leaf(Node<T>* currentNode) const
BEFORE search

Easy fix, copy and paste bool leaf(Node<T>* currentNode) const; before your search function

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top