簡體   English   中英

python中二叉搜索樹的總深度

[英]Total depth of a binary search tree in python

我試圖在 python 中找到 BST 的總深度(這樣根在深度 1,它的孩子深度為 2,那些孩子深度為 3 等),並且總深度是所有這些深度加在一起。 我已經連續嘗試了大約 5 個小時,但無法弄清楚。 這是我迄今為止制作的代碼

class BinaryTreeVertex:
    '''vertex controls for the BST'''

    def __init__(self, value):
        self.right = None 
        self.left = None
        self.value = value

    ...

    def total_Depth(self):
        print ("val:", self.value)
        if self.left and self.right:
            return (self.left.total_Depth()) + 1 and (self.right.total_Depth()) + 1
        elif self.left:
            return 1 + self.left.total_Depth()
        elif self.right:
            return 1 + self.right.total_Depth()
        else:
            return 1
...

tree = BinarySearchTree()     
arr = [6,10,20,8,3]
for i in arr:
    tree.insert(i)
tree.searchPath(20)
print (tree.total_Depth()) #this calls the total_depth from vertex class

生成的樹看起來像這樣。

   6         # Depth 1
___|___
3     10     # Depth 2
    ___|__
    8    20  # Depth 3

但是當我運行它時,它會打印:

val: 6
val: 3
val: 10
val: 8
val: 20
3

這棵樹的 3 實際上應該是 11,但我不知道如何得到它。 請幫忙

編輯:澄清一下,我不是在尋找最大深度,我知道如何找到它。 我需要我解釋的總深度,其中深度是樹的級別。 此處為 11,因為 6 的深度為 1、3 和 10,深度為 2,而 8 和 20 的深度為 3,其中 1+2+2+3+3=11。 我需要它來計算運行時間的比率

你的問題來自這條線。

return (self.left.total_Depth()) + 1 and (self.right.total_Depth()) + 1

使用and將返回提供的最左邊的假值,如果它們都是真值and則返回最右邊的值。 在這種情況下,它實際上最終總是返回self.right.total_Depth() + 1

我推薦的是通過關鍵字參數跟蹤節點深度,我稱之為_depth以強調它應該是私有的,即不是由用戶提供的。

class BinaryTreeVertex:

    ...

    def total_depth(self, _depth=1):

        if self.left and self.right:
            return self.left.total_depth(_depth=_depth + 1) \
                   + self.right.total_depth(_depth=_depth + 1) \
                   + _depth

        elif self.left:
            return _depth + self.left.total_depth(_depth=_depth + 1)

        elif self.right:
            return _depth + self.right.total_depth(_depth=_depth + 1)

        else:
            return _depth

你也可以像這樣縮短它。

def total_depth(self, _depth=1):

    left_depth  = self.left.total_depth(_depth=_depth + 1)  if self.left else 0
    right_depth = self.right.total_depth(_depth=_depth + 1) if self.right else 0

    return left_depth + right_depth + _depth

在這兩種情況下,您都可以獲得這樣的總深度。

tree.total_depth()

暫無
暫無

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

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