首页 > 代码库 > Minimum Depth of Binary Tree

Minimum Depth of Binary Tree

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