zoukankan      html  css  js  c++  java
  • 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。

  • 相关阅读:
    Service、chkconfig命令
    mongoDB 入门
    HTTP 缓存
    MIME类型记录
    CSS3 动画 思维导图
    部署Seafile服务
    AngularJS 学习笔记
    Bootstrap3 学习笔记
    CSS 弹性盒
    传送门(portal)
  • 原文地址:https://www.cnblogs.com/kingshine007/p/11374159.html
Copyright © 2011-2022 走看看