1、前言
題目描述
2室谚、思路
此題比較簡單毡鉴,我們要學會用 DFS 跟 BFS 兩種思路去解決,學會使用這兩種思路很重要秒赤,因為有些題目 DFS 可以解決眨补,但是有些只能是 BFS。
3倒脓、代碼
BFS 思路:
/**
* 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 = 1;
List<TreeNode> queue = new ArrayList<>();
queue.add(root);
while(queue.size() > 0){
int size = queue.size();
// 這種寫法就是將每層分的很清楚
for(int i = 0; i < size; i++){
TreeNode cur = queue.remove(0);
if(cur.left == null && cur.right == null){
return depth;
}
if(cur.left != null){
queue.add(cur.left);
}
if(cur.right != null){
queue.add(cur.right);
}
}
depth++;
}
return depth;
}
}
DFS 思路:
/**
* 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 left = minDepth(root.left);
int right = minDepth(root.right);
// 如果 root 的左右子樹都為空撑螺,則 left、right = 0崎弃;如果任意一個為空甘晤,則 left含潘、right 其中一個為0;
// 如果兩個都不為空线婚,那么選擇其中最小的一個遏弱。
return root.left == null || root.right == null ?
left + right + 1 : Math.min(left, right) + 1;
}
}