# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, val=0, left=None, right=None):
# self.val = val
# self.left = left
# self.right = right
class Solution:
def minDepth(self, root: Optional[TreeNode]) -> int:
if not root: return 0
return self.getMin(root)
def getMin(self, root: 'TreeNode'):
if not root: return 0
left = self.getMin(root.left)
right = self.getMin(root.right)
if not left and right: return right + 1
elif left and not right: return left + 1
else: return min(left, right) + 1
依次判断左右子树深度法,递归法
注意此题与014.二叉树的最大深度相似,但不能直接吗max()改成min()
因为这是没有理解 最小深度 的含义:
最小深度是从根节点到最近叶子节点的最短路径上的节点数量。,注意是叶子节点。
什么是叶子节点,左右孩子都为空的节点才是叶子节点!
所以在得到子树的深度后,需要判断一下,有如下情况
左空,右不空,取右
左不空,右空,取左
左右不空,取最小
最后一种,左右都空,会作为结束递归条件,返回0,不会到达上述逻辑判断这一步。
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, val=0, left=None, right=None):
# self.val = val
# self.left = left
# self.right = right
class Solution:
def minDepth(self, root: Optional[TreeNode]) -> int:
if not root: return 0
queue = collections.deque()
queue.append(root)
depth = 0
while queue:
depth += 1
for i in range(len(queue)):
node = queue.popleft()
# 这一步需要注意,只要发现node的左右孩子皆为空,就意味着找到了最小的深度节点
if not node.left and not node.right: return depth
if node.left: queue.append(node.left)
if node.right: queue.append(node.right)
return depth
层次遍历法,迭代法