【问题标题】:Total depth of a binary search tree in pythonpython中二叉搜索树的总深度
【发布时间】: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


【解决方案1】:

你的问题来自这条线。

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

使用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()

【讨论】:

  • 嗨,不幸的是,我知道如何获得最大深度。我确实在寻找总深度。我需要两者来进行运行时分配
  • 谢谢!我有一个使用参数的想法,但无法弄清楚!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-04-08
  • 2010-12-24
  • 1970-01-01
  • 2013-10-19
  • 2013-02-11
相关资源
最近更新 更多