力扣104题 最大最小深度

寻找树的最大最小深度。

'''
树的最大深度
树的最小深度
'''
import collections
class TreeNode:
    def __init__(self,x):
        self.val = x
        self.left = None
        self.right = None
class Solution:
    def maxdepth_cursion(self,root):                                    #采用递归的方式
        if not root:return 0                                            #直接返回左右子树最大的层数,并加上当前层
        return 1 + max(self.maxdepth_cursion(root.left),self.maxdepth_cursion(root.right))
    def mindepth(self,root):
        if not root:return 0                                            #如果根节点为空,直接返回0
        if not root.left:return 1+self.mindepth(root.right)             #如果左节点为空,则结果是右节点的最小值+1
        if not root.right:return 1+self.mindepth(root.left)             #如果右节点为空,则结果是左节点的最小值+1
        return 1+min(self.mindepth(root.left),self.mindepth(root.right))#如果左右子节点都存在,则返回两个的最小值+1
if __name__ == '__main__':
    solution = Solution()
    root = TreeNode(3)                                                  #构建一棵树
    l = TreeNode(9)
    r = TreeNode(20)
    root.left = l
    root.right = r
    rl = TreeNode(15)
    rr = TreeNode(20)
    r.left = rl
    r.right = rr
    maxDepthResult = solution.maxdepth_cursion(root)
    print('maxDepthResult:',maxDepthResult)
    minDepthResult = solution.mindepth(root)
    print('minDepthResult:',minDepthResult)

 

posted @ 2019-09-02 16:15  weilongyitian  阅读(316)  评论(0编辑  收藏  举报