c++ - 检查树故障的算法

标签 c++

我写这段代码是为了检查有多少节点只剩下儿子

template <class T>
int Tree<T>::onlyLeftSon(Node<T> * current) //check how many left son there are on trehh
{
    if (current == NULL) //empty tree or we finish the tree
        return 0;

    return ( onlyLeftSon(current->left) + onlyLeftSon(current->right) ); // return the sum from left and right

    if (!current->left && !current->right) //if this node not have sons
        return 0;

    if (current->left && !current->right) //if this node not has only left son
        return 1;


}

这个返回0 为什么?

最佳答案

无条件声明:

    return ( onlyLeftSon(current->left) + onlyLeftSon(current->right) );

总是在 current == NULL 检查失败后发生。这意味着您将始终将 onlyLeftSon 计算为 所有 情况下的两个子节点的总和,current == NULL 情况除外,其中你返回 00 + 0 将始终为零。

您可能想要的是:

template <class T>
int Tree<T>::onlyLeftSon(Node<T> * current)
{
    if (current == NULL) //empty tree or we finish the tree
        return 0;

    if (!current->left && !current->right) //if this node not have sons
        return 0;

    if (current->left && !current->right) //if this node not has only left son
        return 1;

    return ( onlyLeftSon(current->left) + onlyLeftSon(current->right) );
}

此时,该算法似乎正在计算父树只有左叶的树中的叶数。这与计算左叶数或一般的左子节点数不同:

    a
  /   \
 b     c

上面的树将返回 onlyLeftSon(tree) == 0。为什么?

  • current == a 时,我们有:
    • current != NULLcurrent->left != NULLcurrent->right != NULL
    • 因此,没有一个 if 语句成功,我们递归到 bc
    • bc 都返回 0,因为它们都没有 child 。

这就是你想要做的吗?还是您要总体上计算每个左叶?

关于c++ - 检查树故障的算法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31013148/

相关文章:

c++ - 使用多个命名空间对 vtable 的 undefined reference

c++ - 如何在C++中存储具有字符串和整数串联的变量

c++ - CURLpp:TLS 握手错误

c++ - 现代 C++ 中的类型删除分配器

c++ - 错误。 C++。 ')' 标记之前的预期主表达式

c++ - 未调用基类构造函数?

c++ - 队列与 mod 操作

c++ - 带有 std::map<T*, U> 的程序是否具有明确定义的行为?

c++ - 如何在运行时查看我的 C 程序的内存布局?

c++ - Ubuntu 18+ 上缺少 Asan 动态运行时