我最开始还在想是否可以提前阻断,但是发现如果不遍历所有节点,就没法确定最小深度。那就没啥好顾虑的,深度优先遍历用起来。给每一个叶子节点(注意是叶子节点)用一个深度值记录下来,用于比较就行了。
class Solution:
def minDepth(self, root: TreeNode) -> int:
if root == None:
return 0
self.depth = 1
self.min_depth = None
def walk(root, num):
if root.left ==None and root.right == None:
self.depth = num
if self.min_depth == None:
self.min_depth = self.depth
else:
self.min_depth = min(self.min_depth, self.depth)
if root.left != None:
walk(root.left, num + 1)
if root.right != None:
walk(root.right, num + 1)
walk(root, 1)
return self.min_depth
但是我的效率并不高。
另外一种迭代写法的DFS是这样的,摘自官方题解写法。主要学习一下if not any(children)这句话,可以判断两个是否都是None,any中有一个参数不是None,any返回就是True,只有在参数都是None的情况下,any返回False,说明当前遍历的节点没有孩子,属于叶节点。这种写法很优雅!
class Solution:
def minDepth(self, root):
"""
:type root: TreeNode
:rtype: int
"""
if not root:
return 0
else:
stack, min_depth = [(1, root),], float('inf')
while stack:
depth, root = stack.pop()
children = [root.left, root.right]
if not any(children):
min_depth = min(depth, min_depth)
for c in children:
if c:
stack.append((depth + 1, c))
return min_depth
作者:LeetCode
链接:https://leetcode-cn.com/problems/minimum-depth-of-binary-tree/solution/er-cha-shu-de-zui-xiao-shen-du-by-leetcode/
来源:力扣(LeetCode)
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。
更加高效的办法是BFS,看了官方题解才明白,原来不需要遍历所有节点,就能知道最小深度的,不需要遍历所有节点。按照层次遍历,只要碰到第一个没有孩子节点的节点,这个节点的深度就是整个树的最小深度。我还是太嫩了啊。
from collections import deque
class Solution:
def minDepth(self, root: TreeNode) -> int:
if root == None:
return 0
queue = deque([(1, root)])
while len(queue)!= 0:
depth, p = queue.popleft()
if not any((p.right, p.left)):
return depth
else:
depth = depth + 1
if p.left != None:
queue.append((depth, p.left))
if p.right != None:
queue.append((depth, p.right))