题目链接:
Minimum Depth of Binary Tree
这道题和Maximum Depth of Binary Tree 基本相似,但是需要注意的是,不是单纯的比较两个子树上的深度,因为当其中一个子树为空时,依旧需要求另一个子树的深度,由此才是最小的。
如的最小深度为2,计算过程为1+min(1,2),左子树的最小深度为1,右子树的最小深度为2。
但是如的最小深度为3,因为它不存在左子树,如果继续通过比较左右子树的话,那么比较结果为0,但是我们需要在叶子节点处判断,所以计算过程为1+2,其中2为右子树的最小深度。
代码如下:
/**
* 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) {
int mindepth = 0;
if(root == null)
return 0;
int minl = minDepth(root.left);
int minr = minDepth(root.right);
if(root.left!=null&&root.right!=null)
mindepth = 1+((minl<minr)?minl:minr);
else
//判断是否存在空的子树
{
if(root.left==null)
mindepth = 1+minr;
else
mindepth = 1+minl;
}
return mindepth;
}
}
1358

被折叠的 条评论
为什么被折叠?



