[英]How do you calculate the height of balanced Binary Search Tree in O(log n) times complexity?
[英]How can you calculate depth of a binary tree with less complexity?
給定一個二叉搜索樹t,很容易使用遞歸來獲得其深度,如下所示:
def node_height(t):
if t.left.value == None and t.right.value == None:
return 1
else:
height_left = t.left.node_height()
height_right = t.right.node_height()
return ( 1 + max(height_left,height_right) )
但是,我注意到它的復雜度呈指數增長,因此當我們有一棵深樹時,它的性能將非常糟糕。 有沒有更快的算法可以做到這一點?
如果將高度作為字段存儲在Node對象中,則可以在將節點添加到樹中時加1(並在刪除過程中減去)。
這將使操作保持恆定的時間來獲取任何節點的高度,但會在添加/刪除操作中增加一些額外的復雜性。
這種擴展來自@ cricket_007在他的回答中提到的內容。
因此,如果執行( 1 + max(height_left,height_right) )
,最終將不得不訪問每個節點,這實際上是O(N)操作。 對於帶有平衡樹的平均情況,您將看到類似T(n) = 2T(n/2) + Θ(1)
。
現在,如果您可以存儲某個節點的高度,則可以將其改進為O(1)的時間。 在這種情況下,樹的高度將等於根的高度。 因此,您需要對insert(value)
方法進行修改。 開始時,根的默認高度為0。要添加的節點的高度為0。對於嘗試添加此新節點時遇到的每個節點,如果需要,將node.height增加1,並確保它設置為1 + max(左孩子的身高,右孩子的身高)。 因此,height函數將僅返回node.height,從而允許常量time 。 插入的時間復雜度也不會改變; 我們只需要一些額外的空間來存儲n
整數值,其中n
是節點數。
顯示以下內容有助於理解我要說的內容。
5 [0]
- insert 2 [increase height of root by 1]
5 [1]
/
/
[0] 2
- insert 1 [increase height of node 2 by 1, increase height of node 5 by 1]
5 [2]
/
/
[1] 2
/
/
[0] 1
- insert 3 [new height of node 2 = 1 + max(height of node 1, height of node 3)
= 1 + 0 = 1; height of node 5 also does not change]
5 [2]
/
/
[1] 2
/ \
/ \
[0] 1 3 [0]
- insert 6 [new height of node 5 = 1 + max(height of node 2, height of node 6)
= 1 + 1 = 2]
5 [2]
/ \
/ \
[1] 2 6 [0]
/ \
/ \
[0] 1 3 [0]
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.