Home > Software design >  Java: For Loop stops after one element in a recursive function
Java: For Loop stops after one element in a recursive function

Time:03-01

I am building a tree structure in java from scratch. For getting the height of my tree I am using a recursive function.

Each note (IP) contains a list of all connections it has, including there parent. My idea was to loop over all children and call the height function again when it's not the parent.

My problem is, that it only calls one child and does not loop over all possible children. Maybe someone can tell me where is my fault.

If one Note has two children and each of them also has another two. It only views the first one at both iterations.

 public int recursiveGetHight(final Node node, Node parent) {
    Node viewPoint = getViewPoint(node);
    int h = 0;
    for (Node child : viewPoint.getChildren()) {
        if (child.getChildren().size() <= 1) {
            return 0;
        } else if(parent == null || child.getValue() != parent.getValue()){
            h = recursiveGetHight(child, viewPoint)   1;
            return h;
        }
    }
    return h;
}

Exempel:

root
    - note 1
        - sub note 1
        - sub note 2
            - x
            - y
    - note 2
        - sub note 1
         - z
        - sub note 2

int h = recurisvHeight(root, null)

result should be 3 but the function returns 2. 

If I at a print command inside the for loop

System.out.println(child);

it shows: note1 sub note 1

CodePudding user response:

It's because you use return, when you make a return your function end. You have to remove the first return = 0 and make an ArrayList of child and replace return h in the by loop by append the child in the list.

  • Related