题目描述:
思路:一开始以为不难,但是直接提交错误。原因:当一个节点只有一个孩子节点时,其深度是孩子结点深度+1,而不是1.
/**
* 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 m1=minDepth(root.left);
int m2=minDepth(root.right);
if(root.left==null||root.right==null) return m1+m2+1;
return Math.min(m1,m2)+1;
}
}