java - BST 不增加 Java 中的节点计数

标签 java nodes binary-search-tree

我正在尝试计算 BST 中的节点数,但是 retval 并未递增。通过调试,我看到每个节点都被访问,但我不确定为什么它没有增加。我知道树中有 3 个节点,它返回 0...

public int countNodes(){
    if (root == null)
        throw new NullPointerException();
    return countNodes(root);
}
private int countNodes(LNode ptr){      
    int retval = 1;
    if (root != null && ptr.right == null && ptr.left == null)
        return retval = 1;
    else
        retval = countNodes(ptr.right) + countNodes(ptr.left) + 1;
    return retval;   
}

我也尝试过不使用 retval 来保存计数:

private in countNodes(LNode ptr){
   if (root != null && ptr.right == null && ptr.left == null)
        return 1;
    else
        return= countNodes(ptr.right) + countNodes(ptr.left) + 1;    
}

最佳答案

这更加准确和相关:

private int countNodes(LNode ptr){      
    if (ptr == null)
        return 0;
    return 1 + countNodes(ptr.left) + countNodes(ptr.right);  
}

关于java - BST 不增加 Java 中的节点计数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21355977/

相关文章:

java - 无法在 Axis2 客户端项目中加载 Rampart 模块

java - 添加方法java

c - 我怎样才能加快我的最小二叉树深度函数?

algorithm - 最优搜索树 : Calculate the cost of the search tree and show that it is not optimal

java - 了解 tomcat docker 文件

java - 检测 JPanel 大小的变化源

java - 我使用泛型实现了什么?

c - 循环链表中的删除函数,当只剩下一个节点时,将下一个和上一个更改为空

关于链接列表中节点的混淆

algorithm - 二进制搜索 ArrayBuffer