Leetcode 111. 二叉樹的最小深度
難度:簡單
用法:遞歸/DFS/BFS
給定一個二叉樹,找出其最小深度。
最小深度是從根節點到最近葉子節點的最短路徑上的節點數量。
說明: 葉子節點是指沒有子節點的節點。
示例:
給定二叉樹
[3,9,20,null,null,15,7]
,3 / \ 9 20 / \ 15 7
返回它的最小深度 2.
題目的重點在於這句話:最小深度是從根節點到最近葉子節點的最短路徑上的節點數量。一定要注意這裏面的深度的計算。
注意1:下方的二叉樹最小深度=2。
注意2:下方的二叉樹最小深度=3。
解法一
遞歸:
# 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
LD = self.minDepth(root.left)
RD = self.minDepth(root.right)
return LD+RD+1 if (not root.left) or (not root.right) else min(LD, RD)+1
解法二
DFS
# 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
stack = [(1, root)]
min_depth = float('inf')
while stack:
depth, node = stack.pop()
if not node.left and not node.right:
min_depth = min(min_depth, depth)
if node.right:
stack.append((depth + 1, node.right))
if node.left:
stack.append((depth + 1, node.left))
return min_depth
方法三
BFS1
# 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
queue = [(1, root)]
while queue:
depth, node = queue.pop(0)
if not node.left and not node.right:
return depth
if node.left:
queue.append((depth + 1, node.left))
if node.right:
queue.append((depth + 1, node.right))
BFS2
更容易理解,事實證明這個是用時最短,內存較少的算法。
# 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 root is None:
return 0
depth = 1
queue = [root]
while queue:
lens = len(queue)
for i in range(lens):
p = queue.pop(0)#切記要先取出
if p.left is None and p.right is None:
return depth
if p.left:
queue.append(p.left)
if p.right:
queue.append(p.right)
depth += 1
return depth