码农知识堂 - 1000bd
  •   Python
  •   PHP
  •   JS/TS
  •   JAVA
  •   C/C++
  •   C#
  •   GO
  •   Kotlin
  •   Swift
  • Leecode DAY16: 二叉树的最大深度 and 二叉树的最小深度 and 完全二叉树的节点个数


    104.二叉树的最大深度(递归)

    终止条件:root == None

    max(左,右子树最大深度) + 1

    1. class Solution:
    2. def maxDepth(self, root: Optional[TreeNode]) -> int:
    3. if not root:
    4. return 0
    5. leftDepth = self.maxDepth(root.left)
    6. rightDepth = self.maxDepth(root.right)
    7. Depth = 1 + max(leftDepth, rightDepth)
    8. return Depth

    111.二叉树的最小深度(递归)

    如果左右子树都存在  那么   minDepth = min(左,右子树最小深度)+ 1

    如果只存在左/右子树 那么 minDepth = min(左 / 右子树最小深度)+ 1

    如果左右子树 都不存在  minDepth = 1

    1. class Solution:
    2. def minDepth(self, root: Optional[TreeNode]) -> int:
    3. if not root:
    4. return 0
    5. if root.right and root.left:
    6. leftDepth = self.minDepth(root.left)
    7. rightDepth = self.minDepth(root.right)
    8. Depth = 1 + min(leftDepth, rightDepth)
    9. elif root.right and not root.left:
    10. Depth = 1 + self.minDepth(root.right)
    11. elif not root.right and root.left:
    12. Depth = 1 + self.minDepth(root.left)
    13. else:
    14. Depth = 1
    15. return Depth

    222.完全二叉树的节点个数(递归)

    1. class Solution:
    2. def countNodes(self, root: Optional[TreeNode]) -> int:
    3. if not root:
    4. return 0
    5. rightN = self.countNodes(root.right)
    6. leftN = self.countNodes(root.left)
    7. return rightN + leftN + 1

    递归的思想 节点数 = 左子树节点数 + 右子树节点数 + 1

     

  • 相关阅读:
    Eureka详解
    从混合云到分布式云 (上篇)
    易基因: Nature Biotech:番茄细菌性青枯病的噬菌体联合治疗|国人佳作
    MLX90640 开发 微型红外成像仪
    LeetCode 11. 盛最多水的容器
    13.状态模式
    MySql 事务隔离实现:
    电脑被格式化怎么恢复数据?电脑格式化后还能恢复数据吗?
    EAP-TLS实验之Ubuntu20.04环境搭建配置(FreeRADIUS3.0)(一)
    快用Python(Pygame)代码燃放起你专属的烟花吧,咝......咻——嘭~
  • 原文地址:https://blog.csdn.net/qq_44189622/article/details/128128197
  • 最新文章
  • 攻防演习之三天拿下官网站群
    数据安全治理学习——前期安全规划和安全管理体系建设
    企业安全 | 企业内一次钓鱼演练准备过程
    内网渗透测试 | Kerberos协议及其部分攻击手法
    0day的产生 | 不懂代码的"代码审计"
    安装scrcpy-client模块av模块异常,环境问题解决方案
    leetcode hot100【LeetCode 279. 完全平方数】java实现
    OpenWrt下安装Mosquitto
    AnatoMask论文汇总
    【AI日记】24.11.01 LangChain、openai api和github copilot
  • 热门文章
  • 十款代码表白小特效 一个比一个浪漫 赶紧收藏起来吧!!!
    奉劝各位学弟学妹们,该打造你的技术影响力了!
    五年了,我在 CSDN 的两个一百万。
    Java俄罗斯方块,老程序员花了一个周末,连接中学年代!
    面试官都震惊,你这网络基础可以啊!
    你真的会用百度吗?我不信 — 那些不为人知的搜索引擎语法
    心情不好的时候,用 Python 画棵樱花树送给自己吧
    通宵一晚做出来的一款类似CS的第一人称射击游戏Demo!原来做游戏也不是很难,连憨憨学妹都学会了!
    13 万字 C 语言从入门到精通保姆级教程2021 年版
    10行代码集2000张美女图,Python爬虫120例,再上征途
Copyright © 2022 侵权请联系2656653265@qq.com    京ICP备2022015340号-1
正则表达式工具 cron表达式工具 密码生成工具

京公网安备 11010502049817号