【问题标题】:How to find the leaf of a binary tree?如何找到二叉树的叶子?
【发布时间】:2014-05-10 05:25:01
【问题描述】:

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

这就是我所拥有的,它给了我一个段错误,并且一直给我从 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;
    }
}

【问题讨论】:

  • 您在哪一行遇到了段错误?您还假设二叉树已排序(即,每个节点都大于左侧,小于或等于右侧)。你的函数是否接收到排序的二叉树?
  • 我按值降序插入元素。
  • 我的意思是self balancing tree。无论哪种方式,如果 x 在不是叶子的节点上,该函数将永远找不到它,因为它只能为叶子节点返回 true。这不是一个完整的答案,但您应该拥有读取if(x==currentNode-&gt;data) return true; 的函数的某些部分(因为您正在搜索值x。)您可能应该单独修复段错误并询问算法,而不是仅仅转储代码.

标签: c++ pointers search recursion binary-tree


【解决方案1】:

在您的搜索功能中,您在不先查看它们是否为 nullptr 的情况下求助于子节点...然后您尝试取消引用数据元素仍然不检查 ​​null。

【讨论】:

    【解决方案2】:

    此外,假设search 中的nullptr 检查已解决,currentNodenullptr 时,leaf 函数返回 true。对于指向不存在的叶子的指针,这是您想要的行为吗?

    【讨论】:

    • 如果左右孩子都是空指针,叶子函数也返回true。我使用三元运算符来返回真或假。也许表达式有问题,它永远不会返回 true?
    • @Revoo 我的看法是search函数中应该有两个base case,否则会有问题。在评论和回答帖子之间已经提到了他们两个。在更新代码、对其进行测试并随后更新问题详细信息之后,我们其他人可能需要查看更多内容并提供帮助。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-01-24
    • 2020-08-23
    • 1970-01-01
    • 2019-11-21
    • 1970-01-01
    相关资源
    最近更新 更多