给定一个二叉树,找出其最小深度。
最小深度是从根节点到最近叶子节点的最短路径上的节点数量。
说明: 叶子节点是指没有子节点的节点。
解法1 递归
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution:
def minDepth(self, root: TreeNode) -> int:
if not root:
return 0
result = list()
self.recur(root, 1, result)
return min(result)
def recur(self, node, height, result):
if not node.left and not node.right:
result.append(height)
return
if node.left:
self.recur(node.left, height + 1, result)
if node.right:
self.recur(node.right, height + 1, result)
解法2 迭代
队列
当出队的节点是叶子节点时,更新最小深度
广度优先遍历完后,返回最小深度
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution:
def minDepth(self, root: TreeNode) -> int:
if not root:
return 0
l = [(root, 1)]
result = float('inf')
while l:
node, h = l.pop(0)
if not node.left and not node.right:
result = min(result, h)
if node.left:
l.append((node.left, h + 1))
if node.right:
l.append((node.right, h + 1))
return result