首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >python中二进制搜索树的总深度

python中二进制搜索树的总深度
EN

Stack Overflow用户
提问于 2018-02-24 10:03:12
回答 1查看 665关注 0票数 1

我试图在python中找到BST的总深度(这样根深度是1,它的子深度是2,那些子深度是3,等等),总和是所有这些深度加在一起。我已经连续尝试了大约5个小时,但还是想不出答案。以下是我到目前为止生成的代码

代码语言:javascript
复制
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

然后,生成的树如下所示。

代码语言:javascript
复制
   6         # Depth 1
___|___
3     10     # Depth 2
    ___|__
    8    20  # Depth 3

但是当我运行它时,它会打印出来:

代码语言:javascript
复制
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。

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2018-02-24 12:36:07

你的问题来自于这一行。

代码语言:javascript
复制
return (self.left.total_Depth()) + 1 and (self.right.total_Depth()) + 1

使用and将返回所提供的最左边的假的值,如果它们都是真的,则返回最右边的值。在这种情况下,它实际上总是返回self.right.total_Depth() + 1

我推荐的是通过一个关键字参数来跟踪节点的深度,我称它为_depth是为了强调它应该是私有的,即不是由用户提供的。

代码语言:javascript
复制
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

你也可以像这样缩短它。

代码语言:javascript
复制
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

在这两种情况下,你都可以像这样得到总深度。

代码语言:javascript
复制
tree.total_depth()
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/48958605

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档