Reputation: 3257
I have tried to write a method called getHeight()
to calculate the height of am N-ary tree. My attempt does not work. This is the tree interface I am using:
public interface MyTree {
Tree getSubTree(int i) ;//returns a subtree
boolean isLeaf() ;//returns true if the node is a leaf
int getDegree() ;
}
This is the piece of code that I have written:
public int getHeight(){
for(int i = 0 ; i<getDegree()-1 ; ++i){
if(isLeaf()){
return 0;
}else{
return 1 + Math.Max(getSubtree(i).getHeight() , getSubtree(i+1).getHeight() ;
}
}
}
How can I fix this method?
Upvotes: 0
Views: 871
Reputation: 4257
Your issue is here:
return 1 + getSubtree(i).getHeight();
you are returning from the method as soon as you calculate 1 + the height of a single sub tree. What you actually need to do is call getHeight()
on EVERY subtree, and return 1 + the maximum of each of those. (This could be simplified if your tree has any balance properties.)
For example, if the tree you are calling this on has three subtrees, with heights 2, 4, and 5, you code will call getHeight()
on the first subtree and see 2, then immediately return 3, instead of checking getHeight()
on the remaining subtrees to find that there is a taller subtree (the one with height 5).
Upvotes: 5