Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/oop/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python:二叉树中的最大深度_Python_Oop_Binary Tree_Depth - Fatal编程技术网

Python:二叉树中的最大深度

Python:二叉树中的最大深度,python,oop,binary-tree,depth,Python,Oop,Binary Tree,Depth,我刚刚介绍了Python中的oop和二叉树,但在尝试实现最大深度方法时遇到了问题。它似乎没有给我正确的答案,它给了我1,而数字应该大得多,或者我完全误解了什么。我在下面添加了一部分代码 class Node: def __init__(self, value, left=None, right=None): self.left = left self.right = right self.value = value self.count = 1 def

我刚刚介绍了Python中的oop和二叉树,但在尝试实现最大深度方法时遇到了问题。它似乎没有给我正确的答案,它给了我1,而数字应该大得多,或者我完全误解了什么。我在下面添加了一部分代码

class Node:
def __init__(self, value, left=None, right=None):
    self.left = left
    self.right = right
    self.value = value
    self.count = 1

    def depth(self):
        if self.left:
            left_depth = self.left.depth()
        else:
            left_depth = 0
        right_depth = self.right.depth() if self.right else 0

        print(max(left_depth, right_depth) + 1)



tree = createTree(words) # list of words
tree.depth()
应该是

        return max(left_depth, right_depth) + 1
因此,调用
.depth()
方法时,实际上会返回一个值

然后,在最后,当你真正想要一个结果时:

print(tree.depth())

另外,使用两种不同的if-else结构有点奇怪

        left_depth = self.left.depth() if self.left else 0
        right_depth = self.right.depth() if self.right else 0

可以很好地工作并且更加简洁。

print
不是
return
。正如@user2357112上面所说的,您应该
返回
值,而不是
打印
它。
        left_depth = self.left.depth() if self.left else 0
        right_depth = self.right.depth() if self.right else 0