BinaryTree计数留下无限的loof

时间:2015-11-09 12:30:45

标签: recursion binary-tree stack-overflow infinite-loop

我在二叉树类中编写了countLeaf方法来计算来自root的每个叶子。

然而,它给了我堆栈溢出错误,但我无法弄清楚我做错了什么。

这是我的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' ...和stackoverflow错误

为什么它不断重复原始根而不是向左或向右?

1 个答案:

答案 0 :(得分:1)

public int countLeaf(Node node)替换为public int countLeaf(Node root)

我相信这会有所帮助。

无论如何,永远不会使用变量节点