python求二叉树深度

废话不多说 直接上代码

# 用于生生一个类似于二叉树的数据
class Node:
    def __init__(self, value=None, left=None, right=None):
        self.value = value
        self.left = left
        self.right = right


def tree_depth(tree):
    if tree is None:
        return 0
    left_depth = tree_depth(tree.left)
    right_depth = tree_depth(tree.right)
    return left_depth + 1 if left_depth > right_depth else right_depth + 1


trr = Node('D', left=Node('B', Node('A'), Node('C')), right=Node('E', right=Node('G', Node('F'))))
a = tree_depth(trr)

  

上一篇:0104. Maximum Depth of Binary Tree (E)


下一篇:MyDLNote-360camera: ECCV 2020 结合室内全景图像的三维布局和深度预测