[Leetcode]Minimum Depth of Binary Tree
来源:互联网 发布:unity3d 序列帧动画 编辑:程序博客网 时间:2024/05/17 07:35
Given a binary tree, find its minimum depth.
The minimum depth is the number of nodes along the shortest path from the root node down to the nearest leaf node.
判断树的最小深度~树的最小深度指的是从根节点到最近的叶节点的距离,所以如果某一个节点只有左子树或右子树,我们不能取它左右子树中小的作为深度,因为其并非叶节点,要注意处理这种情况~下面代码是递归的解法~
class Solution: # @param root, a tree node # @return an integer def minDepth(self, root): if root is None: return 0 if root.left is None: return self.minDepth(root.right) + 1 if root.right is None: return self.minDepth(root.left) + 1 return min(self.minDepth(root.left), self.minDepth(root.right)) + 1
知道递归解法还不够,最好也能写出非递归解法~代码如下~(注意:python中list.pop(0)时间复杂度为O(n),所以下面curr = queue.pop(0)这句不是很高效)
class Solution: # @param root, a tree node # @return an integer def minDepth(self, root): if root is None: return 0 queue = [root, None]; depth = 1 while queue: curr = queue.pop(0) if curr == None: # note: do not increase depth if queue # is empty; if queue: queue.append(None) depth += 1 else: if curr.left is None and curr.right is None: return depth if curr.left: queue.append(curr.left) if curr.right: queue.append(curr.right)
0 0
- 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
- LeetCode - Minimum Depth of Binary Tree
- 【Leetcode】Minimum Depth of Binary Tree
- LeetCode | Minimum Depth of Binary Tree
- LeetCode - Minimum Depth of Binary Tree
- 追逐自己的梦想----------辅助制作第十二课:选怪功能封装
- 计数排序、桶排序和基数排序
- 长沙微信营销到底优势何在?
- 图像处理中两种基本的插值算法(最邻近插值法和双线性内插法)
- IO多路复用机制--select、poll、epoll & poll-wait
- [Leetcode]Minimum Depth of Binary Tree
- LeetCode题解—TwoSum
- Eclipse与VS2012 实现ExtJs智能提示
- m进制转换为n进制-任意进制转换算法
- iBeacon系列:一、iBeacon的简介及作用
- 实验四
- 包含min函数的栈
- 直方图均衡化的一些小小的抄袭
- linux 学习之九、Linux 磁盘与文件系统管理(3)