首页 技术 正文
技术 2022年11月15日
0 收藏 462 点赞 4,642 浏览 1155 个字

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.

Note: A leaf is a node with no children.

Example:

Given binary tree [3,9,20,null,null,15,7],

    3
/ \
9 20
/ \
15 7

return its minimum depth = 2.

2018/0813 update: 不能直接用l or r, 因为我们要先选小的, 如果小的是空, 然后才需要去判断那个大的. 所以需要min 及max, 而且min应该在前面.

思路为DFS recursive, 但是需要注意的是, 比如[1,2] 应该return 2, 但是上面知会return 1. 所以需要return min(l,r) or max(l, r), 因为有一边有, 另一边没有的时候要返回有的.

 2020/0509 update: 直接用BFS,碰到第一个leaf,return当时的height即可。

1. Constraints

1) can be none => 0

2. Ideas

BFS T: O(n)   S: O(n)

DFS recursive    T: O(n)   S: O(n)

3, Code

class Solution:
def minDepth(self, root):
if not root: return 0
l, r = self.minDepth(root.left), self.minDepth(root.right)
return 1+ (min(l, r) or max(l, r))

=> more elegant

class Solution:
def minDepth(self, root):
if not root: return 0
d = map(self.minDepth, (root.left, root.right))
return 1 + (min(d) or max(d))

利用BFS

class Solution:
def miniDepth(self, root):
if not root: return 0
queue = collections.deque([(root, 1)])
while queue:
node, height = queue.popleft()
if not node.left and not node.right:
return height
if node.left:
queue.append((node.left, height + 1))
if node.right:
queue.append((node.right, height + 1))

4. Test cases

1) [1,2]

2) [3,9,20,null,null,15,7]

相关推荐
python开发_常用的python模块及安装方法
adodb:我们领导推荐的数据库连接组件bsddb3:BerkeleyDB的连接组件Cheetah-1.0:我比较喜欢这个版本的cheeta…
日期:2022-11-24 点赞:878 阅读:9,076
Educational Codeforces Round 11 C. Hard Process 二分
C. Hard Process题目连接:http://www.codeforces.com/contest/660/problem/CDes…
日期:2022-11-24 点赞:807 阅读:5,552
下载Ubuntn 17.04 内核源代码
zengkefu@server1:/usr/src$ uname -aLinux server1 4.10.0-19-generic #21…
日期:2022-11-24 点赞:569 阅读:6,400
可用Active Desktop Calendar V7.86 注册码序列号
可用Active Desktop Calendar V7.86 注册码序列号Name: www.greendown.cn Code: &nb…
日期:2022-11-24 点赞:733 阅读:6,176
Android调用系统相机、自定义相机、处理大图片
Android调用系统相机和自定义相机实例本博文主要是介绍了android上使用相机进行拍照并显示的两种方式,并且由于涉及到要把拍到的照片显…
日期:2022-11-24 点赞:512 阅读:7,812
Struts的使用
一、Struts2的获取  Struts的官方网站为:http://struts.apache.org/  下载完Struts2的jar包,…
日期:2022-11-24 点赞:671 阅读:4,894