top button
Flag Notify
    Connect to us
      Site Registration

Site Registration

Create a function to calculate the height of an n-ary tree.

+1 vote
613 views
Create a function to calculate the height of an n-ary tree.
posted Nov 3, 2016 by anonymous

Share this question
Facebook Share Button Twitter Share Button LinkedIn Share Button

1 Answer

0 votes

Finding the height is in fact no different for N-ary trees than for any other type of tree. A leaf node has height 0, and a non-leaf node has height one more than the tallest of its children.

Have a recursive function that in pseudocode does this in Java:

public static int getHeight(Node n){
    if(n.isLeaf()){
         return 0;
    }else{
        int maxDepth = 0;

        foreach(Node child : n.getChildren()){
            maxDepth = Math.max(maxDepth, getHeight(child));
        }

        return maxDepth + 1;
    }
}
answer Nov 4, 2016 by Manikandan J
...