【Leetcode】【python】Minimum Depth of Binary Tree
来源:互联网 发布:淘宝借呗 编辑:程序博客网 时间:2024/06/06 03:49
题目大意
求二叉树的最小深度
解题思路
联想到求最大深度,递归到最深处往上层慢慢+1。
代码
class Solution(object): def minDepth(self, root): """ :type root: TreeNode :rtype: int """ if root == None: return 0 if root.left != None and root.right == None: return self.minDepth(root.left)+1 if root.left == None and root.right != None: return self.minDepth(root.right)+1 return min(self.minDepth(root.left),self.minDepth(root.right))+1
总结
这题有意思的是,并不能直接将求最大深度的max改为min就完了,有很多坑在里面。一开始我以为只要将[],[0],[1,2]等情况考虑掉就可以了,其实在只有一边又子节点的情况下,是仍然需要遍历的。
例如:
要分几种情况考虑:
1. 树为空,则为0。
2. 根节点如果只存在左子树或者只存在右子树,则返回值应为左子树或者右子树的(最小深度+1)。
3. 如果根节点的左子树和右子树都存在,则返回值为(左右子树的最小深度的较小值+1)。
阅读全文
0 0
- 【Leetcode】【python】Minimum Depth of Binary Tree
- 【LeetCode with Python】 Minimum Depth of Binary Tree
- [leetcode: Python] 111. Minimum Depth of Binary Tree
- 【leetcode】111. Minimum Depth of Binary Tree(Python & C++)
- LeetCode: Minimum Depth of Binary Tree
- [Leetcode] Minimum Depth of Binary Tree
- LeetCode : Minimum Depth of Binary Tree
- leetcode 31: Minimum Depth of Binary Tree
- [LeetCode] Minimum Depth of Binary Tree - BFS
- [LeetCode] Minimum Depth of Binary Tree - DFS
- 【leetcode】Minimum Depth of Binary Tree
- LeetCode:Minimum Depth of Binary Tree
- [LeetCode]Minimum Depth of Binary Tree
- [Leetcode]Minimum Depth of Binary Tree
- [leetcode]Minimum Depth of Binary Tree
- Leetcode: Minimum Depth of Binary Tree
- LeetCode-Minimum Depth of Binary Tree
- [leetcode] Minimum Depth of Binary Tree
- RxJS
- linux下的守护进程
- 【Leetcode】【python】Balanced Binary Tree
- numpy.searchsorted 用法
- 动态规划入门-数字三角形
- 【Leetcode】【python】Minimum Depth of Binary Tree
- 码云,git使用 教程
- Java编程入门基础笔记-New
- 以后 博文 要做 中文对照,利于国际化,利于自己熟悉英语。
- uva679
- 【文献阅读】dropout distillation
- Vue进阶-入门
- Making the Grade (bzoj1592)
- unity角色摄像机实际坐标变了,但是不移动的问题