簡體   English   中英

二叉搜索樹的最大高度

[英]max height of binary search tree

所以我需要找到一個二叉樹的最大高度,但是由於某種原因,下面提供的代碼結果偏離了1。例如,如果最大高度為3,則下面的代碼將給我2。如果最大高度為4結果將是3。我不確定為什么嗎? 根不考慮最大高度的計算,因此我將leftCounter和rightCounter設置為0。有什么想法嗎?

public int getMaxHeight(BST.TreeNode<E> n) {
    if(n == null) {
        return 0;
    }
    int leftCounter = 0;
    int rightCounter = 0;
    if(n.left != null) {
        leftCounter = getMaxHeight(n.left) +1 ;
    }
    if(n.right != null) {
        rightCounter = getMaxHeight(n.right) +1 ;
    }

    if(leftCounter > rightCounter) {
        return leftCounter;
    }   
    else 
        return rightCounter;    

}

由於元素5,9,11,此二叉樹的最大高度應為3 根不計入最大高度。

        15
   _____|____
   10       21 
___|___    __|__ 
9    14   16   24
                |__
                  25

您的代碼實際上返回正確的值; 只是您誤解了樹高的含義。 高度是從根到葉的最長路徑上的數,而不是路徑上的節點數 所以下面的樹

        3
   _____|____
   4         5 
___|___    __|__ 
6     7    8   9

的高度為2,而不是3。您要查找的是樹中的層數 ,而不是高度。

public int getNumberOfLevels(BST.TreeNode<E> n) {
    if(n == null) return 0;
    int left = getNumberOfLevels(n.left);
    int right = getNumberOfLevels(n.right);
    return 1 + Math.max(left, right);
}  

您可以通過1初始化leftCounter和RightCounter。原因是if(n == null)-> false
表示高度至少為1

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM