Jonas Scholz
Jonas Scholz

Reputation: 555

Print data of Nodes with multiple children [Java]

Hey to all Stackoverflowers!:D

This is my first question ever on stackoverflow, I appreciate any advice for my next questions!

I want to print out the data of all nodes in a tree data structure. I already have some code, but I get weird results.

-Every node can have multiple children, those are stored in a List of nodes
-I always start with the root

Here is my Code:

    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);
    } 
}

But if I call this function my programm does not print out all nodes. I know this since I print the data while creating the nodes, I get this:

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

If I print it out with my recursive function, I get this:

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

-47 is the parent, with the children -13 and -5, -5 just doesnt want to get printed tho.

If I print it out manually, like root.children.children...get(i) whatever, I can access both kids, with the right data... I seriously have no clue where my fault is in my code, would be great if someone can help me... I am sure im just kinda blind :D

I also tried some other trees, sometimes this error wont show up, sometimes it will...

The Tree-Structure looks like this: enter image description here

Thanks for your help, I hope my question is understandable

Upvotes: 2

Views: 932

Answers (1)

Stefan Haustein
Stefan Haustein

Reputation: 18813

You are changing the current node variable (= blatt) while you are iterating the children by re-assigning blatt in the loop. This means that you continue at the child's second child (instead of the second direct child) after the first child was printed. Fix:

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);
  } 
}

Upvotes: 2

Related Questions