Minimum Depth of Binary Tree

Given a binary tree, find its minimum depth.

The minimum depth is the number of nodes along the shortest path from the root node down to the nearest leaf node.

Example

Given a binary tree as follow:

  1
 / \ 
2   3
   / \
  4   5
The minimum depth is 2.

思路

  1. 此题的思路与maximum depth很类似,但是由于求的是minDepth,所以如果左右子树中有一个为空会返回0,这时我们是不能算做有效深度的。
  2. 所以分成了三种情况
    1)左子树为空: 返回右子树depth + 1;
    2)右子树为空: 返回左子树depth + 1;
    3)左右子树都不为空:返回Math.min(helper(root.left), helper(root.right)) + 1;
    4) 当然,如果左右子树都为空的话,就会返回1。
/**
 * 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
     */
    private int min = Integer.MAX_VALUE;
    
    public int minDepth(TreeNode root) {
        // write your code here
        if (root == null) {
            return 0;
        }
        
        int result = helper(root);
        return result;
    }
    
    private int helper(TreeNode root) {
        if (root == null) {
            return 0;
        }
        
        if (root.left == null) {
            return helper(root.right) + 1;
        }
        
        if (root.right == null) {
            return helper(root.left) + 1;
        }
        
        // right, left are not null
        return Math.min(helper(root.left), helper(root.right)) + 1;
    }
}

你可能感兴趣的:(Minimum Depth of Binary Tree)