不废话,搞清楚定义就好,本质仍然是4种情况的判定。定义是:如果任何一只child为null,则minDepth是有腿的那条腿的高度。
代码:
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
public class Solution {
public int minDepth(TreeNode root) {
if(root==null) return 0;
if(root.left==null && root.right==null) return 1;
else if(root.left==null && root.right!=null) return 1+minDepth(root.right);
else if(root.left!=null && root.right==null) return 1+minDepth(root.left);
else return 1+Math.min(minDepth(root.left), minDepth(root.right));
}
}