打印多个孩子的节点数据[Java]

时间:2017-04-19 16:09:46

标签: java recursion data-structures tree

嘿所有的Stackoverflowers!:D

这是我在stackoverflow上的第一个问题,我感谢您对我的下一个问题的任何建议!

我想打印出树数据结构中所有节点的数据。我已经有了一些代码,但是我得到了奇怪的结果。

- 每个节点都可以有多个子节点,这些子节点存储在节点列表中
- 我总是从根

开始

这是我的代码:

    public static void printTree(Knoten blatt){      
    Aufgabe1.Gewichte = Aufgabe1.Gewichte + blatt.Gewicht;
    System.out.println(blatt.Gewicht);

    for(int i=0;i<blatt.children.size();i++) {
        blatt = blatt.children.get(i);
        printTree(blatt);
    } 
}

但如果我调用此函数,我的程序不会打印出所有节点。 我知道这一点,因为我在创建节点时打印数据,我得到了这个:

3.0
27.0
-6.0
-7.0
10.0
-5.0
-47.0
-13.0
-5.0

如果我用递归功能将其打印出来,我就明白了:

3.0
27.0
-6.0
-7.0
10.0
-5.0
-47.0
-13.0

-47是父母,孩子-13和-5,-5只是不想打印。

如果我手动打印出来,比如root.children.children ... get(i)无论如何,我可以使用正确的数据访问这两个孩子...... 我真的不知道我的错误在我的代码中,如果有人可以帮助我会很棒... 我相信我只是有点盲目:D

我也尝试过其他一些树,有时候这个错误不会出现,有时它会......

Tree-Structure看起来像这样: enter image description here

感谢您的帮助,我希望我的问题可以理解

1 个答案:

答案 0 :(得分:2)

当您通过在循环中重新分配blatt来迭代子节点时,您正在更改当前节点变量(= blatt)。这意味着在第一个孩子被打印后,您继续在孩子的第二个孩子(而不是第二个直接孩子)。修正:

public static void printTree(Knoten blatt) {      
  Aufgabe1.Gewichte = Aufgabe1.Gewichte + blatt.Gewicht;
  System.out.println(blatt.Gewicht);

  for(int i = 0; i < blatt.children.size(); i++) {
    Knoten kind = blatt.children.get(i);  // Don't overwrite blatt here
    printTree(kind);
  } 
}