java - 一种计算二叉搜索树中具有 2 个子节点的节点数的方法

标签 java binary-search-tree tree-traversal

这是我能想到的最好的办法,但它仍然不起作用,因为即使有多个节点有两个子节点,它也会返回 1。

int countTwoChildren(Node node)
{
    if(node==null) {
        return 0;
    }
    if(node.left!=null && node.right!=null) {
        return 1;
    }
    return countTwoChildren(node.left) + countTwoChildren(node.right);
}

谁能发现上面这段代码有什么错误吗?

最佳答案

缺少一件小事:

int countTwoChildren(Node node)
{
    if(node==null) {
        return 0;
    }
    if(node.left!=null && node.right!=null) {
        return 1 + countTwoChildren(node.left) + countTwoChildren(node.right);
    }
    return countTwoChildren(node.left) + countTwoChildren(node.right);
}

关于java - 一种计算二叉搜索树中具有 2 个子节点的节点数的方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10756403/

相关文章:

c - 二叉搜索树的删除函数出错

algorithm - 使用集合和二叉搜索树解析和构建 S 表达式

c - 后序树遍历中的段错误

c - 是否可以获取当前节点之上的节点?

java - 如何为非英语语言运行 GATE/JAPE?

java - 为什么在 Java 锁实现中没有使用 synchronized 关键字?

java - 如何在 Java 中打印出数组的偶数索引?

algorithm - 保存列表的良好数据结构

scala - Scala 中的惰性树遍历迭代器

java - 父类(super class)中的静态变量用于控制多个子类