題目含義解釋:
給定一個二叉樹,找出其最小深度。
最小深度是從根節點到最近葉子節點的最短路徑上的節點數量。
說明: 葉子節點是指沒有子節點的節點。
遞歸算法求二叉樹最小深度
/**
* 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 = Integer.MAX_VALUE;
if (root.left != null) {
min = Math.min(min, minDepth(root.left));
}
if (root.right != null) {
min = Math.min(min, minDepth(root.right));
}
return min + 1;
}
}
非遞歸思路實現二叉樹的最小深度
import java.util.*;
import javafx.util.*;
/**
* 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;
}
int depth = Integer.MAX_VALUE;
Queue<Pair<TreeNode, Integer>> queue = new LinkedList<>();
queue.add(new Pair(root, 1));
while (!queue.isEmpty()) {
Pair<TreeNode, Integer> pair = queue.poll();
TreeNode curr = pair.getKey();
int currDepth = pair.getValue();
if (curr.left == null && curr.right == null) {
depth = Math.min(depth, currDepth);
} // 左右節點均爲null則表明當前節點是葉子節點,故此時才更新depth的大小
if (curr.left != null) {
queue.add(new Pair(curr.left, currDepth + 1));
}
if (curr.right != null) {
queue.add(new Pair(curr.right, currDepth + 1));
}
}
return depth;
}
}
重點是明白此處的深度指的是到達葉子結點的最短路徑節點個數。