您的位置:首页 > 其它

LeetCode——111. Minimum Depth of Binary Tree

2017-09-05 21:39 369 查看
问题描述:

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;如果这个点两个子节点都有,那么这个点的层数应该是左子节点和右子节点间取最小的。

public int minDepth(TreeNode root) {
if(root == null)
return 0;

int left = minDepth(root.left);
int right = minDepth(root.right);
return (left == 0 || right == 0) ? left + right + 1: Math.min(left,right) + 1;
}


  后来想了想,又把原来的改了一下,其实从上到下也是可以的,只不过要在当前节点是叶子结点,即(root.left == null && root.right == null)时,才对最小层数进行更新,其他情况是继续往下遍历。

private int minLevel = 99999999;

public int minDepth(TreeNode root) {
if(root == null)
return 0;

//上面是答案的方法,我自己想了想,在自己原方法上改进一下,形成了新的
//其实就是在更新最小层数时,要当前节点是叶子结点的情况下,才能进行更新
searchDepth(1, root);
return minLevel;
}

public void searchDepth(int level, TreeNode root) {
if(root.left == null && root.right == null) {
if(level < minLevel) {
minLevel = level;
}
return;
}
if(root.left != null)
searchDepth(level+1, root.left);
if(root.right != null)
searchDepth(level+1, root.right);
}


  这道题还是比较简单的,所以今天的解释也是比较简单。

  依旧,谢谢大家观看我的博客,如果有不明白的地方或者文中有错误的地方,欢迎大家指出,谢谢!
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  leetcode 二叉树