1、題目描述
https://leetcode-cn.com/problems/minimum-depth-of-binary-tree/
給定一個二叉樹,找出其最小深度。 最小深度是從根節點到最近葉子節點的最短路徑上的節點數量。
說明: 葉子節點是指沒有子節點的節點。
同類題:DFS-LeetCode104. 二叉樹的最大深度 https://blog.csdn.net/IOT_victor/article/details/107021517
2、代碼詳解
遞歸寫法:關鍵是搞清楚遞歸結束條件
# Definition for a binary tree node.
class TreeNode(object):
def __init__(self, x):
self.val = x
self.left = None
self.right = None
class Solution(object):
def minDepth(self, root):
'''
葉子節點的定義是左孩子和右孩子都爲 null 時叫做葉子節點
1. 當 root 節點左右孩子都爲空時,返回 1
2. 當 root 節點左右孩子有一個爲空時,返回不爲空的孩子節點的深度
3. 當 root 節點左右孩子都不爲空時,返回左右孩子較小深度的節點值
'''
if not root:
return 0
left_min = self.minDepth(root.left)
right_min = self.minDepth(root.right)
if not root.left and not root.right: # 情況 1
return 1
elif not root.left or not root.right: # 情況 2
return left_min + 1 if root.left else right_min + 1
else: # 情況 3
return min(left_min, right_min) + 1
其他解法:
BFS迭代,DFS迭代