求二叉树深度 利用前序遍历思维以及递归 python实现

树的深度:也称为树的高度,树中所有结点的层次最大值称为树的深度

# class TreeNode:
#     def __init__(self, x):
#         self.val = x
#         self.left = None
#         self.right = None


def RemaxDepth(root, deep):
    if not root: return deep - 1
    return max(RemaxDepth(root.left, deep + 1), RemaxDepth(root.right, deep + 1))


def maxDepth(root):
    stack = []
    deg = 0
    n = 0
    while stack or root:
        while root:
            n += 1
            stack.append((root, n))  # 记录下当前深度
            root = root.left
        root, n = stack.pop()
        root = root.right
        deg = max(deg, n)
    return deg


print(RemaxDepth(root, 1))
print(maxDepth(root))

你可能感兴趣的:(From,Python,二叉树,python,算法,数据结构)