這道題是LeetCode裏的第111道題。
題目描述:
給定一個二叉樹,找出其最小深度。
最小深度是從根節點到最近葉子節點的最短路徑上的節點數量。
說明: 葉子節點是指沒有子節點的節點。
示例:
給定二叉樹
[3,9,20,null,null,15,7]
,3 / \ 9 20 / \ 15 7返回它的最小深度 2.
遞歸解決。調用最小值函數 Math.min(x, y) 或者 三目運算符 expression ? true : false。
解題代碼:
/**
* 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);
return (left!=0&&right!=0)?1+Math.min(left,right):1+left+right;
}
}
提交結果:
個人總結:
不使用變量的效率:
/**
* 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 minDepth(root.right) + 1;
if(root.right == null && root.left != null)
return minDepth(root.left) + 1;
return minDepth(root.left) + 1 > minDepth(root.right) + 1 ? minDepth(root.right) + 1 : minDepth(root.left) + 1;
}
}