您的位置:首页 > 其它

LeetCode-Minimum Depth of Binary Tree

2015-02-26 03:10 351 查看
DFS 里面的if else写错了 第一段是正确代码,第二段是错误的。错误的写法就是因为多写了一个else,就不会再进right那边了。

public class Solution {
public int minDepth(TreeNode root) {
if ( root == null )
return 0;
int min = Integer.MAX_VALUE;
min = DFS (root, min, 1);
return min;
}
public int DFS (TreeNode node, int min, int depth){
if ( depth < min ){
if ( node.left == null && node.right == null ){
min = depth;
}
else if ( node.left != null){
min = DFS (node.left, min, depth + 1);
}
if ( node.right != null)
min = DFS (node.right, min, depth + 1);
}
return min;
}
}

新写的recursive:

public class Solution {
public int minDepth(TreeNode root) {
if ( root == null )
return 0;
int left = minDepth( root.left);
int right = minDepth ( root.right);
if ( left == 0 || right == 0 ) //<span style="color:#ff0000;">这个判断很重要,假如只有一边没有子叶,那不应该选小的那边的值</span>
return left+right+1;
return Math.min(left,right) +1;
}
}iterative:用bfs level order traversal方法,需要记录一个level值 假如扫到这一行 出现叶子 就直接return level。每一行一个for循环,将这一行全一个一个poll出来 并且每个的孩子offer入队。
public class Solution {
public int minDepth(TreeNode root) {
Queue<TreeNode> que = new LinkedList<TreeNode>();
if ( root == null)
return 0;
que.offer(root);
int level = 1;
while(!que.isEmpty()){
int num = que.size();
for ( int i = 0; i < num; i ++ ){
TreeNode cur = que.poll();
if ( cur.left == null && cur.right == null)
return level;
if( cur.left != null )
que.offer(cur.left);
if( cur.right != null )
que.offer(cur.right);
}
level ++;
}
return 0;
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: