我正在尝试计算 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/