Python实现二叉树的最小深度的两种方法
作者:求兵 时间:2022-05-24 03:30:17
找到给定二叉树的最小深度
最小深度是从根节点到最近叶子节点的最短路径上的节点数量
注意:叶子节点没有子树
Example:
Given binary tree [3,9,20,null,null,15,7],
3
/ \
9 20
/ \
15 7
return its minimum depth = 2.
1:算法遍历二叉树每一层,一旦发现某层的某个结点无子树,就返回该层的深度,这个深度就是该二叉树的最小深度
def minDepth(self, root):
"""
:type root: TreeNode
:rtype: int
"""
if not root:
return 0
curLevelNodeList = [root]
minLen = 1
while curLevelNodeList is not []:
tempNodeList = []
for node in curLevelNodeList:
if not node.left and not node.right:
return minLen
if node.left is not None:
tempNodeList.append(node.left)
if node.right is not None:
tempNodeList.append(node.right)
curLevelNodeList = tempNodeList
minLen += 1
return minLen
2:用递归解决该题和"二叉树的最大深度"略有不同。主要区别在于对“结点只存在一棵子树”这种情况的处理,在这种情况下最小深度存在的路径肯定包括该棵子树上的结点
def minDepth(self, root):
"""
:type root: TreeNode
:rtype: int
"""
if not root:
return 0
if not root.left and root.right is not None:
return self.minDepth(root.right)+1
if root.left is not None and not root.right:
return self.minDepth(root.left)+1
left = self.minDepth(root.left)+1
right = self.minDepth(root.right)+1
return min(left,right)
算法题来自:https://leetcode-cn.com/problems/minimum-depth-of-binary-tree/description/
来源:https://blog.csdn.net/qiubingcsdn/article/details/82419605
标签:Python,二叉树,最小深度
0
投稿
猜你喜欢
解决SQLServer最大流水号的两个好方法
2009-01-13 14:15:00
asp一个空间绑定N个域名的方法!
2009-03-08 18:32:00
python关键字传递参数实例分析
2023-08-24 04:28:34
解决python3 pika之连接断开的问题
2021-09-28 18:40:09
python实现域名系统(DNS)正向查询的方法
2021-03-26 17:20:57
sqlserver 触发器学习(实现自动编号)
2012-10-07 10:58:03
Python切片操作去除字符串首尾的空格
2023-08-08 19:19:21
教你怎样打造SQL Server2000的安全策略
2009-01-23 14:03:00
浅析Python中的getattr(),setattr(),delattr(),hasattr()
2022-11-10 08:26:41
为google量身定做的sitemap生成代码asp版
2011-04-06 10:43:00
PHP开发技巧之PHAR反序列化详解
2023-11-15 02:23:45
Python中的字符串查找操作方法总结
2021-06-13 12:21:46
python的继承知识点总结
2022-12-10 11:21:28
python实现逢七拍腿小游戏的思路详解
2021-02-28 23:44:29
详解go中的引用类型
2023-08-28 06:02:31
Django1.11自带分页器paginator的使用方法
2021-07-04 12:44:23
在Python的一段程序中如何使用多次事件循环详解
2023-04-08 03:33:28
弹出网页窗口全详细攻略
2008-04-18 12:10:00
php之php.ini配置文件讲解案例
2023-06-11 18:19:06
极简主义网站设计:寓丰富于简单
2009-12-07 21:37:00