Saturday, January 10, 2015

LeetCode 111: 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.
/**
 * 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;
            
        // Root node can't be regarded as leaf node,
        // So we should consider if root doesn't have left node or right node.
        // However, if root doesn't have both, return 1.
        if (root.left==null && root.right!=null)
            return minDepth(root.right) + 1;
        else if (root.left!=null && root.right==null)
            return minDepth(root.left) + 1;
        else
            return Math.min(minDepth(root.left), minDepth(root.right)) + 1;
    }
}

No comments:

Post a Comment