题目描述:

第一次提交:

class Solution(object):
def minDepth(self, root):
"""
:type root: TreeNode
:rtype: int
"""
if not root:
return 0
if root.left and root.right:
return min(self.minDepth(root.left)+1,self.minDepth(root.right)+1)
if not root.left and root.right:
return self.minDepth(root.right)+1
if not root.right and root.left:
return self.minDepth(root.left)+1
if not root.left and not root.right:
return 1

优化后:

class Solution(object):
def minDepth(self, root):
"""
:type root: TreeNode
:rtype: int
"""
if not root: return 0
if not root.left or not root.right:
return 1 + max(self.minDepth(root.right), self.minDepth(root.left))
else:
return 1 + min(self.minDepth(root.right), self.minDepth(root.left))

方法二:广度优先 O(N)

from collections import deque
class Solution:
def minDepth(self, root):
if not root:
return 0
else:
node_deque = deque([(1, root),]) while node_deque:
depth, root = node_deque.popleft()
children = [root.left, root.right]
if not any(children):
return depth
for c in children:
if c:
node_deque.append((depth + 1, c))

最新文章

  1. 《C#高级编程》学习总结之LINQ
  2. WordCount示例深度学习MapReduce过程(1)
  3. mongodb--java操作
  4. 【转】十二个移动App云测试服务盘点
  5. poj-2403-cup
  6. android测试之——mokeyrunner上(二)
  7. 10个漂亮的jQuery日历插件下载【转载】
  8. 深入浅出数据结构C语言版(12)——平衡二叉查找树之AVL树
  9. 【JAVA零基础入门系列】Day12 Java类的简单应用
  10. C# 内存模型
  11. Quartz实现分布式可动态配置的定时任务
  12. 做rl_abs过程中遇到的问题
  13. 15Linux_DHCP_Postfix_Dovecot_LDAP
  14. win10 uwp 商业游戏 1.2.1
  15. Java基础_0310:引用传递
  16. myeclise中创建maven web程序
  17. 使用自定义验证组件库扩展 Windows 窗体
  18. r指定位置插入一列
  19. Django(基础篇)
  20. html-blogsdemo

热门文章

  1. 升级python后yum命令出错
  2. C++ 求最大公因数和最大公倍数模板
  3. 【Luogu】【关卡2-12】递推与递归二分(2017年10月)
  4. JavaWeb开发之一《Tomcat服务器的部署、安装及应用》
  5. mysql5.7问题:[Note] InnoDB: Waiting for page_cleaner to finish flushing of buffer pool
  6. leetcode-163周赛-1261-在污染的二叉树中查找元素
  7. jQuery冒泡事件阻止
  8. (转)OpenFire源码学习之九:OF的缓存机制
  9. JS闭包的详解
  10. 其它课程中的python---5、Pandas处理数据和读取数据