如何找到二叉树的叶结点

How to find the leaf of a binary tree?

本文关键字:结点 叶结点 何找 二叉树      更新时间:2023-10-16

我正在编写一个具有搜索功能的二叉树。该函数应该接受一个参数x,该参数表示要搜索的值,一旦找到它,确定它是否是叶子。如果没有找到该值,则返回false。

这是我所拥有的,它给了我一个segfault,并且刚刚给了我从1到100的每个值的错误返回。二叉树初始化为100个值

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 < currentNode->data)
    {
    if ((leaf(currentNode)) == true)
        { 
          return true;
        }
    else 
    {
    search(currentNode->left, x);   
    }
    }

//Right Subtree Search
else if (x >= currentNode->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

void remove(Node<T>* &currentNode, const T& x)
{
}
bool leaf(Node<T>* currentNode) const 
{
    if (currentNode != nullptr)
    {
    return ((currentNode->left == nullptr && currentNode->right == nullptr) ? true : false);        
    }
    else 
    {
        return true;
    }
}

另外,当currentNodenullptr时,leaf函数返回true,假设searchnullptr的检查已解决。这是你想要的指向不存在的叶子的指针的行为吗?

在您的搜索函数中,您求助于子节点而不首先查看它们是否为nullptr…然后尝试取消引用数据元素,但仍然不检查是否为null。