c++ - 为什么这个递归函数的行为与预期的不同?

标签 c++ if-statement recursion binary-tree

我正在写一棵二叉树,我被困在一个搜索函数上,该函数接受一个值 x 并确定它是否是树中的叶子。

这是我的:

bool search(Node<T>* &currentNode, const T& x) const
{
    /* Base Case */
    if ( currentNode != nullptr && (leaf(currentNode) == true) && currentNode->data == x )
    {
        return true;
    }

    /* Recursive Case */
    else {

        if (currentNode != nullptr)
        {
        search(currentNode->left, x);
        search(currentNode->right, x);
        }

        //If first if condition is not met for all values then value must not exist
        return false;

        }


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

代码总是返回false,为什么第一个IF语句从未被触发?

编辑: 代码调用搜索:

for (int i = 0; i < 101; i++)           
            if ((t.search(i) == true) ? cout << "LEAF FOUND: " << i  << endl : cout << " NOT A LEAF: " << i << endl);

最佳答案

处理递归可能很棘手 :D。

除非根节点是叶子,否则您的代码将始终返回 return false 您的代码返回 true 给调用的函数,而不是一直返回到原始调用者(在递归之前)

假设您的树具有三个元素,并且该项目位于左叶中 所以在根节点中你用左节点调用自己所以它返回 true 给调用者(根节点),根节点对此不做任何事情并继续执行。

这可以通过添加一个 if 语句来检查您调用的函数的返回值来简单地解决

if (currentNode != nullptr)
{
    if(search(currentNode->left, x)) return true;
    if(search(currentNode->right, x)) return true;
}
return false;

关于c++ - 为什么这个递归函数的行为与预期的不同?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22754072/

相关文章:

c++ - 为什么我在使用 boost::asio::null_buffers 时无法获取发送端点?

c++ - 使用默认构造函数初始化对象

php - 关于 PHP 中的 if 语句

css - 我可以检查父元素在 sass 中有特定的类吗?

java - 递归检查数组是否包含 0 (java)

C++:使用 Libxml 解析 XML 时出现问题

java - 存储分析信标的最有效方法是什么?

javascript - 在javascript中检查字符串中是否只有标点符号

recursion - 使用 impl trait 返回递归迭代器时溢出评估需求

python - 有序遍历AVL树 : Name not defined