【问题标题】:BinaryTree count leaves infinite loof二叉树计数留下无限循环
【发布时间】: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


    【解决方案1】:

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

    我相信它会有所帮助。

    无论如何,变量 node 从未使用过。

    【讨论】:

      猜你喜欢
      • 2020-08-27
      • 1970-01-01
      • 2021-12-10
      • 1970-01-01
      • 1970-01-01
      • 2015-05-16
      • 1970-01-01
      • 1970-01-01
      • 2017-12-07
      相关资源
      最近更新 更多