码农知识堂 - 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

     

  • 相关阅读:
    Java环境安装即配置
    C# 使用 RSA 加密算法生成证书签名产生“The system cannot find the file specified”异常
    数学建模——最优连接(基于最小支撑树)
    centos7内存过高排查
    第01章 网络数据采集入门
    C程序设计内容与例题讲解 -- 第四章--选择结构程序设计第二部分(第五版)谭浩强
    用实践案例告诉你,什么样的人能够在网络上赚钱
    UCIe技术——概览索引
    面试突击72:输入URL之后会执行什么流程?
    张鑫溢:9.1黄金晚间实时行情趋势分析及黄金原油独家操作建议指导.
  • 原文地址: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号