111 Minimum Depth of Binary Tree

Question:

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.

Lesson Learned

minimum depth 不再是左右两棵树的比较,而是到leaf的长度的比较,不是leaf的长度都不能count。因此要判断左右子树是否有一个为空。如果为空,则不能让它经历撞墙的过程,因为撞了墙就会有一个该子树的返回值影响结果。因此要用if语句来防止左右子树之一为空的那个空子树撞墙。

Code:

/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
public class Solution {
    public int minDepth(TreeNode root) {
        return helper(root);
    }
    private int helper(TreeNode root) {
        if (root == null) {
            return 0;
        }
        if (root.left == null && root.right == null) {
            return 1;
        } else if (root.right == null) {
            return 1 + helper(root.left);
        } else if (root.left == null) {
            return 1 + helper(root.right);
        }
        return 1 + Math.min(helper(root.left), helper(root.right));
    }
}