【发布时间】:2015-11-09 12:30:45
【问题描述】:
我在我的二叉树类中编写了 countLeaf 方法来计算从根开始的每一片叶子。
但是,它给了我堆栈溢出错误,但我不知道我做错了什么。
这是我的 binaryTree 中的 countLeaf 类
public int countLeaf(Node node){
if(root == null){return 0;} // this part work when I create null Tree
else if(root.left == null && root.right == null){
return 1; //this work when I create tree without left and right
}
else {
System.out.print(root.data); // check infinite loop
return countLeaf(root.left) + countLeaf(root.right);
}
}
这是我的主线
public static void main (String[] args){
BinaryTree a = new BinaryTree("A?",
new BinaryTree("B?",
new BinaryTree("D"),
new BinaryTree("E")),
new BinaryTree("C?",
new BinaryTree("E"),
new BinaryTree("F")));
System.out.print(a);
int n = a.countLeaf(a.root);
}
当我运行它时,它给了我
A?A?A?A?A?A?A?A?A?A?A?A?A? ...和stackoverflow错误
为什么它一直重复原始根而不是跟随左或右??
【问题讨论】:
标签: recursion binary-tree stack-overflow infinite-loop