104-111-二叉树最大深度和最小深度

题目:求一个二叉树的最大深度和最小深度

def max_depth(root):
    if not root:
        return 0
    return 1 + max(max_depth(root.left),max_depth(root.right))

def min_depth(root):
    if not root:
        return 0
    if not root.left:
        return 1+min_depth(root.right)
    if not root.right:
        return 1+min_depth(root.left)
    return 1 + min(min_depth(root.left),min_depth(root.right))

注:

采用分治法,最大深度即为左右子树的最大深度+1;最小深度即为左右子树的最小深度+1。最小深度的时候还要注意,如果节点只有左子树或右子树,需要返回另一半子树的深度+1,这是比求最大深度要增加的部分,否则就会将该节点的深度求为1。

posted @ 2019-08-18 21:58  尘世中一个迷途小书童  阅读(138)  评论(0编辑  收藏  举报