victorio
victorio

Reputation: 6646

How can I count the highest level in a tree with recursion?

So there's the mission. We have a class, call NODE, the instance is "node". This node has a lot of children, and these children have a lot of children too, etc etc. How could I count the highest level in this tree? etc:

the highest level in this tree, is 4 (child1.1.2.1's level, node's level is 0) Please help me! I know, I should use recursive methods, but I don't know how, if anyone could solve this problem, and write a code... please... Thank You! The method should start with:

public int maxLevel(NODE node){...

Upvotes: 2

Views: 2497

Answers (2)

arshajii
arshajii

Reputation: 129507

You can try something like this:

public static int maxLevel(Node node) {
    if (node.children.length == 0) return 1;

    int max = maxLevel(node.children[0]);
    for (int i = 1 ; i < node.children.length ; i++) {
        int n = maxLevel(node.children[i]);
        if (n > max) max = n;
    }

    return max + 1;
}

where node.children is the array consisting of the child-nodes of node.

Upvotes: 1

Paul Bellora
Paul Bellora

Reputation: 55213

This method returns a level of 1 for the base case (having 0 children):

public int maxLevel() {
    int maxChildLevel = 0;
    for (Node child : children) {
        maxChildLevel = Math.max(maxChildLevel, child.maxLevel());
    }
    return maxChildLevel + 1;
}

This example is meant to declare maxLevel as an instance method of Node, so there's no need for it to take a Node as an argument.

Upvotes: 3

Related Questions