主题思想: 递归, 找根节点到叶子节点的最小路径长度。
AC 代码:
/**
* 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 node is leaf return 1
if(root.left==null&&root.right==null)
return 1;
int lh=0,rh=0;
if(root.left!=null) lh=1+minDepth(root.left);
if(root.right!=null) rh=1+minDepth(root.right);
//means no left sub
if(lh==0) return rh;
//mens no right sub;
if(rh==0) return lh;
return Math.min(lh,rh);
}
}