【发布时间】:2018-02-24 02:03:12
【问题描述】:
我正在尝试在 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你想要完成什么?这总是会返回右分支的深度加一。你可能想要max((self.left.total_Depth()) + 1, (self.right.total_Depth()) + 1) -
你是如何计算出你想要的返回值为 11 的?我认为您混淆了树值和树深度,它们是完全独立的事物。您想要树的深度还是沿路径遍历的值的总和?
-
我非常怀疑您是否想对每个级别的深度进行 sum(在任何情况下,总和只是 D(D+1)/2 )。大概你只想找到最大深度。
-
无论如何,您的错误是
expr1 and expr2。 Olivier 的回答用三行代码展示了实现深度函数的简洁方式。
标签: python tree binary-search-tree