Java 递归倒计时函数
我试图计算二叉树的叶子数,但是递归函数总是返回0 有人能帮我吗Java 递归倒计时函数,java,Java,我试图计算二叉树的叶子数,但是递归函数总是返回0 有人能帮我吗 public static int countLeaves(BinaryTree tree) { if (tree.emptyTree()) { System.out.println("im here "); return 0; } if (tree.getLeft() == null && tree.getRight() == null) {
public static int countLeaves(BinaryTree tree) {
if (tree.emptyTree()) {
System.out.println("im here ");
return 0;
}
if (tree.getLeft() == null && tree.getRight() == null) {
System.out.println("but I'M NEVER HERE "); // doesn't get in
return 1;
} else {
return countLeaves(tree.getLeft()) + countLeaves(tree.getRight());
}
}
以下代码行似乎是致命缺陷:
if (tree.emptyTree()){
我认为当你真的想返回1作为基本情况时,这个情况将是正确的。请尝试以下代码:
public static int countLeaves(BinaryTree tree) {
if (tree.getLeft() == null && tree.getRight() == null) {
return 1;
}
else {
return countLeaves(tree.getLeft()) +
countLeaves(tree.getRight());
}
}
请参见代码中的解释注释
public static int countLeaves(/* @Nullable */ BinaryTree tree) {
if (tree == null) {
// Guardian clause
return 0;
} else if (tree.getLeft()==null && tree.getRight()==null) {
// This is a leaf node ==> count this leaf.
return 1;
} else {
// This is a non-leaf node ==> recursive call.
return countLeaves(tree.getLeft()) + countLeaves(tree.getRight());
}
}
在您的代码中,您为相同的情况复制了if
条件(我现在假设tree.emptyTree()
返回true
当且仅当两个子项都为null
)。因此,第二个如果
是不可到达的->但是我从来都不在这里
另一个问题是当
left
或right
为null
(另一个节点为non-null
)时,您没有处理这种情况。这只有在处理完整的二叉树时才行 你的tree.emptyTree()
代码看起来像什么?类BinaryTree
是什么?你的emptyTree()代码和你的if(tree.getLeft()==null和&tree.getRight()==null)有什么区别?取一个有一个节点的二叉树。使用您熟悉的IDE进行调试(如果没有,请尝试Eclipse)。取一个有两个节点的二叉树,执行相同的操作,依此类推,直到得到正确的结果。这是学习的唯一途径但是@JohnDonn是对的,使用调试器是理解发生了什么的方法。您的代码基本上看起来是正确的。我认为检查tree.emptyTree()
是个问题。投票被否决了,因为即使有(简短的)解释性评论,对于初学者来说,仅仅给他们工作代码也没有帮助。@Tim,这是真的,第一个if
子句是个问题,但另一个问题是当离开(或者只是right
)子项为null
。感谢您的回答。问题是如果(tree.getLeft()==null&&etc…不返回true..我必须使用tree.getLeft().emptyTree()代替。