码迷,mamicode.com
首页 > 其他好文 > 详细

LeetCode - Minimum Depth of Binary Tree

时间:2015-04-29 01:57:40      阅读:114      评论:0      收藏:0      [点我收藏+]

标签:

        求二叉树的最小深度。

      

/**
 * Definition for binary tree
 * 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;
        int l = minDepth(root.left);
        int r = minDepth(root.right);
        if(l==0)
            return r+1;
        else if(r==0)
            return l+1;
        else 
            return r<l? r+1:l+1;
    }
    
}

     谁能告诉我下面这个代码错在哪里了?

  

/**
 * Definition for binary tree
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
public class Solution {
    public static int MIN = 9999999;
	public static int minDepth(TreeNode root) {
        if(root == null)
            return 0;
        dfs(root, MIN, 1);
        return MIN;
    }
	public static void dfs(TreeNode root, int min, int cnt) {
        if(root == null) return ;
        if(root.left==null && root.right==null) {
            if(min > cnt) {
                min = cnt;
                MIN = min;
            }
            return ;
        }
        dfs(root.left, min, cnt+1);
        dfs(root.right, min, cnt+1);
        return ;
    }
    
}

 

LeetCode - Minimum Depth of Binary Tree

标签:

原文地址:http://www.cnblogs.com/wxisme/p/4464494.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!