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

Minimum Depth of Binary Tree

时间:2017-05-31 10:14:30      阅读:254      评论:0      收藏:0      [点我收藏+]

标签:missing   selected   bin   bsp   treenode   root   question   value   nod   

This question is a little bit harder than the Max Depth. We only compare the depth of the leaf node. If it is missing one side, this level shouldn‘t be considered. 

/**
 * Definition of TreeNode:
 * public class TreeNode {
 *     public int val;
 *     public TreeNode left, right;
 *     public TreeNode(int val) {
 *         this.val = val;
 *         this.left = this.right = null;
 *     }
 * }
 */
public class Solution {
    /**
     * @param root: The root of binary tree.
     * @return: An integer.
     */
    public int minDepth(TreeNode root) {
        // write your code here
        
        if (root == null) {
            return 0;
        }
        
        int left = minDepth(root.left);
        int right = minDepth(root.right);
        
        int minDepth = 0;
        
        if ((left == 0 && right != 0) || (left != 0 && right == 0)) {
            minDepth = Math.max(left, right);    
        } else {
            minDepth = Math.min(left, right);
        }
        
        return minDepth + 1;
    }
}

The clearer way to do it:

/**
 * Definition of TreeNode:
 * public class TreeNode {
 *     public int val;
 *     public TreeNode left, right;
 *     public TreeNode(int val) {
 *         this.val = val;
 *         this.left = this.right = null;
 *     }
 * }
 */
public class Solution {
    /**
     * @param root: The root of binary tree.
     * @return: An integer.
     */
    public int minDepth(TreeNode root) {
        // write your code here
        if (root == null) {
            return 0;
        }
        
        return getMin(root);
    }
    
    private int getMin(TreeNode root) {
        //The null will not be selected since we will get min later
        if (root == null) {
            return Integer.MAX_VALUE; 
        }
        
        //If it is leaf node, count as 1 depth
        if (root.left == null && root.right == null) {
            return 1;
        }
        
        return Math.min(getMin(root.left), getMin(root.right)) + 1;
    }
}

 

Minimum Depth of Binary Tree

标签:missing   selected   bin   bsp   treenode   root   question   value   nod   

原文地址:http://www.cnblogs.com/codingEskimo/p/6922411.html

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