題目描述
給定一個二叉樹,找出其最小深度。
最小深度是從根節點到最近葉子節點的最短路徑上的節點數量。
說明: 葉子節點是指沒有子節點的節點。
示例:
給定二叉樹 [3,9,20,null,null,15,7],
3
/ \
9 20
/ \
15 7
返回它的最小深度 2.
思路
往下遍歷時深度+1,到達葉子節點時,更新最小的深度即可。
代碼
class Solution {
int minDepth = Integer.MAX_VALUE;
public int minDepth(TreeNode root) {
if (root == null) return 0;
preOrder(root, 0);
return minDepth;
}
private void preOrder(TreeNode root, int depth) {
if (root == null) return ;
depth++;
if (root.left == null && root.right == null) {
minDepth = Math.min(depth, minDepth);
return;
}
preOrder(root.left, depth);
preOrder(root.right, depth);
}
}