简体   繁体   English

一元树的高度

[英]height of a N-ary tree

I have tried to write a method called getHeight() to calculate the height of am N-ary tree. 我尝试编写一种名为getHeight()的方法来计算am N元树的高度。 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? 如何解决此方法?

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. 您只要计算出1 +单个子树的高度,就会从该方法返回。 What you actually need to do is call getHeight() on EVERY subtree, and return 1 + the maximum of each of those. 您实际需要做的是在每个子getHeight()调用getHeight() ,并返回1 +每个子树的最大值。 (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). 例如,如果要在其上调用的树具有三个子树,其高度分别为2、4和5,则代码将在第一个子树上调用getHeight()并看到2,然后立即返回3,而不是检查getHeight()在其余的子树上找到一个更高的子树(高度为5的子树)。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM