您的位置:首页 > 其它

111 Minimum Depth of Binary Tree

2017-03-26 12:14 120 查看
我当时还把这两道题放在一起考过别人,就是为了迷惑对方,以为把max改成min就行,这就是典型的错误的理解,因为只有当左子和右子都不为null时才能有min,只有一个为null,那么depth因为就是另一分支。。。说到底,还是要非常明确minDepth的定义:从root到叶子节点最短的分支,所包含的节点的个数。。。

这题和上一题都是递归调用自身。

之前的代码,I am a 认真 boy:

/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
import java.util.List;
import java.util.ArrayList;
//import java.lang.Math;
public class Solution {
public int minDepth(TreeNode root) {
/* if(root==null) return 0;
List<TreeNode> list = new ArrayList<TreeNode>();
list.add(root);
int depth=1; // 注意起始值是1,不是0,因为是指这条path上node的数量。
while(true){
List<TreeNode> current = new ArrayList<TreeNode>();
for(TreeNode node : list){ // 轮一层,做几个判断。。。
if(node.left==null&&node.right==null) return depth;
if(node.left!=null) current.add(node.left);
if(node.right!=null) current.add(node.right);
}
depth++;
list=current;
} // solution1, iterration, this works, but too slow, let me try the recursion*/

if(root==null) return 0;
if(root.left==null && root.right==null) return 1;
if(root.left==null) return 1+minDepth(root.right);
if(root.right==null) return 1+minDepth(root.left);
if(root.left!=null && root.right!=null) return (1 + Math.min(minDepth(root.left), minDepth(root.right)));
return 0; // solution2, recursive, this works faster, but may use more space

/* // solution3, same idea with solution2, but more concise code
if(root==null) return 0;
else return (Math.min(minDepth(root.left), minDepth(root.right)) +1); // 事实证明,这样是对minDepth来说是不行的,因为当只有一个子树的时候,该节点的高度只能是子树的高度,不能是null的高度。
// 但是呢,这个精简的写法,对于maxDepth是见效的。。。可以一试。。*/

}
}

今天的代码,3 min, 就是分清楚4种情况就好。
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
public class Solution {
public int minDepth(TreeNode root) {
if(root==null) return 0;

if(root.left==null && root.right==null) return 1;
else if(root.left==null && root.right!=null) return 1+minDepth(root.right);
else if(root.left!=null && root.right==null) return 1+minDepth(root.left);
else return 1+Math.min(minDepth(root.left), minDepth(root.right));
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: