当前位置: 首页 > news >正文

代码随想录27期|Python|Day16|二叉树|104.二叉树的最大深度|111.二叉树的最小深度|222.完全二叉树的节点个数

 二叉树专题,重点掌握后续的递归和中间节点的处理。

104. 二叉树的最大深度 - 力扣(LeetCode)

本题在前一章已经解决了层序遍历的解法,现在来聊一下递归法。

首先需要明确两个概念:深度和高度。(注意,起始位置的值都是1)

        深度:从root开始,到当前位置所在节点的层数;

        高度:从底层叶子节点开始,到当前所在节点的层数。

再来说一下选择什么顺序来遍历。

        前序:从root出发,直接找的是深度;

        后序:从叶子节点出发,返回给root节点高度。

也就是说,不管选择哪一种,中间节点都是单独处理的

后序遍历

按照递归的书写三部曲,可以写出后序遍历的方法。

# Definition for a binary tree node.
# class TreeNode(object):
#     def __init__(self, val=0, left=None, right=None):
#         self.val = val
#         self.left = left
#         self.right = right
class Solution(object):def maxDepth(self, root):""":type root: TreeNode:rtype: int"""# 后序遍历(Version 1)# step1 确定返回值类型:TreeNode# step2 确定终止条件:当前节点是空if not root:return 0else:# step3 单层处理:按照“左右中”的顺序,先遍历左节点高度,再遍历右节点高度,汇总到中间节点取较大值,再加1(因为当前中间节点也算作一层)left_height = self.maxDepth(root.left)right_height = self.maxDepth(root.right)return max(left_height, right_height) + 1# 精简递归(Version 2)return 0 if not root else max(self.maxDepth(root.left), self.maxDepth(root.right)) + 1

前序遍历

要麻烦很多,还涉及到回溯算法,十分甚至九分的不推荐

# Definition for a binary tree node.
# class TreeNode(object):
#     def __init__(self, val=0, left=None, right=None):
#         self.val = val
#         self.left = left
#         self.right = right
class Solution(object):def maxDepth(self, root):""":type root: TreeNode:rtype: int"""# 递归(前序遍历)res = 0if not root:return 0self.getdepth(root, 1)return resdef getdepth(self, node, depth):res = max(depth, res)if node.left == None and node.right == None:returnif node.left:depth += 1self.getdepth(node.left, depth)depth -= 1  # 回溯算法if node.right:depth += 1self.getdepth(node.right, depth)depth -= 1return

559. N 叉树的最大深度 - 力扣(LeetCode)

和上面相似的一道题,只用了递归+左右中的后序遍历。

只需要用for遍历所有孩子节点(其实就是上面分别判断左节点和右节点的推广)。

"""
# Definition for a Node.
class Node(object):def __init__(self, val=None, children=None):self.val = valself.children = children
"""class Solution(object):def maxDepth(self, root):""":type root: Node:rtype: int"""if not root:return 0max_depth = 1  # 在排除顶部节点是空的时候初始化最大值是1# 遍历所有的孩子节点for child in root.children:# 注意在每次比较的时候+ 1,表示计算上了中间节点max_depth = max(self.maxDepth(child) + 1, max_depth)return max_depth

 111. 二叉树的最小深度 - 力扣(LeetCode)

本题需要注意的是和上面求解最大值需要遍历到底不一样,本题需要遍历到第一个叶子节点,也就是左右子树都没有的第一个节点。

依然使用后序遍历

递归法 

# Definition for a binary tree node.
# class TreeNode(object):
#     def __init__(self, val=0, left=None, right=None):
#         self.val = val
#         self.left = left
#         self.right = right
class Solution(object):def minDepth(self, root):""":type root: TreeNode:rtype: int"""# 递归法if not root:return 0else:# 左left_height = self.minDepth(root.left)# 右right_height = self.minDepth(root.right)# 中if root.left and root.right == None:  # 左子树存在,右子树不存在return left_height + 1if root.right and root.left == None:  # 右子树存在左子树不存在return right_height + 1# 遇到叶子节点返回到中间节点的最小值return min(left_height, right_height) + 1

精简递归

把求解左右高度的简化到中间处理的返回值处。

            # 左left_height = self.minDepth(root.left)# 右right_height = self.minDepth(root.right)

222. 完全二叉树的节点个数 - 力扣(LeetCode)

递归(后序遍历)

# Definition for a binary tree node.
# class TreeNode(object):
#     def __init__(self, val=0, left=None, right=None):
#         self.val = val
#         self.left = left
#         self.right = right
class Solution(object):def countNodes(self, root):""":type root: TreeNode:rtype: int"""# 当作普通二叉树if not root:return 0# 左left_num = self.countNodes(root.left)# 右right_num = self.countNodes(root.right)# 中return left_num + right_num + 1# 精简版if not root:return 0return self.countNodes(root.left) + self.countNodes(root.right) + 1

利用完全二叉树递归

题干当中还特别说明了是完全二叉树,所以我们可以使用完全二叉树在左右外侧深度相等的时候是满二叉树的性质来统计。

简单概括就是:如果这一层的左子树的左深度和右子树的右深度相等,那么就可以判断现在这是满二叉树。

利用这个性质,我们就很容易可以判断满足满二叉树的条件。

# Definition for a binary tree node.
# class TreeNode(object):
#     def __init__(self, val=0, left=None, right=None):
#         self.val = val
#         self.left = left
#         self.right = right
class Solution(object):def countNodes(self, root):""":type root: TreeNode:rtype: int"""# 利用完全二叉树if not root:return 0# 判断是满二叉树直接输出leftnode = root.leftrightnode = root.rightleft_depth, right_depth = 0, 0while leftnode:leftnode = leftnode.leftleft_depth += 1while rightnode:rightnode = rightnode.rightright_depth += 1if left_depth == right_depth:return (2 << left_depth) - 1  # 2 << 1 = 2 ^ 2# 普通二叉树正常递归输出return self.countNodes(root.left) + self.countNodes(root.right) + 1

第16天完结🎉

http://www.lryc.cn/news/262436.html

相关文章:

  • ༺༽༾ཊ—设计-简介-模式—ཏ༿༼༻
  • Matplotlib快速入门,Python通用的绘图工具库上手
  • Linux 基本语句_16_Udp网络聊天室
  • 使用ffmpeg命令进行视频格式转换
  • Mac安装Adobe AE/pr/LR/ai/ps/au/dw/id 2024/2023报错问题解决(常见错误:已损坏/2700/146/130/127)
  • Python三级 每周练习题31
  • 【DataSophon】大数据服务组件之Flink升级
  • Android笔记(十八):面向Compose组件结合Retrofit2和Rxjava3实现网络访问
  • mybatis中oracle的sql没走索引导致特别慢(未加jdbcType的)
  • QT自带打包问题:无法定位程序输入点?metaobject@qsound
  • 7.3 lambda函数
  • dcoker-compose一键部署EFAK —— 筑梦之路
  • 音视频:Ubuntu下安装 FFmpeg 5.0.X
  • 【LSM tree 】Log-structured merge-tree 一种分层、有序、面向磁盘的数据结构
  • 配置OSPF与BFD联动示例
  • 01到底应该怎么理解“平均负载”
  • jmeter,动态参数之随机数、随机日期
  • uniApp常见知识点-问题答案
  • 云原生基础入门概念
  • 一个 tomcat 下如何部署多个项目?附详细步骤
  • pycharm强制让terminal停止执行的快捷键
  • MFC(Microsoft Foundation Classes)中 MessageBox
  • 如何让.NET应用使用更大的内存
  • 【从零开始学习JVM | 第九篇】了解 常见垃圾回收器
  • Wordle 游戏实现 - 使用 C++ Qt
  • Python 爬虫开发完整环境部署,爬虫核心框架安装
  • 汽车标定技术(十三)--标定概念再详解
  • PostgreSQL常用命令
  • 使用python脚本部署k8s集群
  • 【C语言】操作符详解(四):结构成员访问操作符