二叉树计数离开无限循环
BinaryTree count leaves infinite loof
我在我的二叉树中写了 countLeaf 方法 class 来计算从根开始的每一片叶子。
然而,它给了我堆栈溢出错误,但我不知道我做错了什么。
这是我的 binaryTree
中的 countLeaf class
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? ...和计算器错误
为什么它一直重复原始根而不是向左或向右??
将 public int countLeaf(Node node)
替换为 public int countLeaf(Node root)
。
相信会有帮助。
无论如何,变量 node 永远不会被使用。
我在我的二叉树中写了 countLeaf 方法 class 来计算从根开始的每一片叶子。
然而,它给了我堆栈溢出错误,但我不知道我做错了什么。
这是我的 binaryTree
中的 countLeaf classpublic 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? ...和计算器错误
为什么它一直重复原始根而不是向左或向右??
将 public int countLeaf(Node node)
替换为 public int countLeaf(Node root)
。
相信会有帮助。
无论如何,变量 node 永远不会被使用。