1 題目描述
給定一個二叉樹,找出其最小深度。
最小深度是從根節點到最近葉子節點的最短路徑上的節點數量。
說明: 葉子節點是指沒有子節點的節點。
示例:
給定二叉樹 [3,9,20,null,null,15,7],
返回它的最小深度 2.
來源:力扣(LeetCode)
鏈接:https://leetcode-cn.com/problems/minimum-depth-of-binary-tree
著作權歸領釦網絡所有。商業轉載請聯繫官方授權,非商業轉載請註明出處。
2 解題思路
採用的方法是遞歸,遞歸題目的詳細瞭解和總結,可以看另一篇博客 套路俘虜–遞歸–的芳心,就是你,沒錯了~~,非常簡潔容易理解
第一步,確定終止條件,樹爲空或者只有一層的時候就終止
第二步,本層遞歸應該做什麼?節點不爲空的時候,判斷最小的深度
第三步,返回值,返回最小深度
- 複雜度分析
時間複雜度:我們訪問每個節點一次,時間複雜度爲 O(N) ,其中 N 是節點個數。
空間複雜
度:最壞情況下,整棵樹是非平衡的,例如每個節點都只有一個孩子,遞歸會調用 N (樹的高度)次,因此棧的空間開銷是 O(N) 。但在最好情況下,樹是完全平衡的,高度只有 log(N),因此在這種情況下空間複雜度只有 O(log(N)) 。
3 解決代碼
- java代碼
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
class Solution {
public int minDepth(TreeNode root) {
// 第一步,確定終止條件,樹爲空或者只有一層的時候就終止
if(root == null)
return 0;
if((root.left == null) && (root.right == null))
return 1;
//第二步,本層遞歸應該做什麼?節點不爲空的時候,判斷最小的深度
int min_depth = Integer.MAX_VALUE;
if(root.left != null){
min_depth = Math.min(minDepth(root.left),min_depth);
}
if(root.right != null){
min_depth = Math.min(minDepth(root.right), min_depth);
}
//第三步,返回值,返回最小深度
return min_depth + 1;
}
}
- python 代碼
# 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
children = [root.left, root.right]
if not any (children):
return 1
#第二步,本層遞歸應該做什麼?節點不爲空的時候,判斷最小的深度
min_depth = float("inf")
for c in children:
if c:
min_depth = min(self.minDepth(c), min_depth)
#第三步,返回值,返回最小深度
return min_depth +1