题目如下:
Given a binary tree, find its minimum depth.
The minimum depth is the number of nodes along the shortest path from the root node down to the nearest leaf node.
注意的是,这里求的是最小深度。这个深度是指“根节点到叶子节点的路径距离”,其中叶子节点一定是要重点强调的。假如一个二叉树是[1,2],那么,它的最小深度是2,不是1。因为,只有没有任何子节点的节点才叫做叶子节点,虽然根节点没有右子节点,但是它有左子节点,所以它不是叶子节点。而二叉树[1]的最小深度就是1,因为根节点没有任何子节点,所以它既是根节点也是叶子节点,直接计算就可以得到正确结果。
这道题思路也是比较简单的,我们只需要求出一个节点子节点的最小深度,然后再加上1就是这个节点的最小深度,用递归再合适不过了。直接放已Accepted的代码,如下所示:
public int minDepth(TreeNode root) {
if(root==null){
return 0;
}else if(root.left!=null && root.right!=null){
int min_left = minDepth(root.left);
int min_right = minDepth(root.right);
return min_left>min_right?min_right+1:min_left+1;
}else if(root.left!=null){
return minDepth(root.left)+1;
}else{
return minDepth(root.right)+1;
}
}