2014年5月9日星期五

Binary Tree Recursive Solution - Minimum Depth of Binary Tree

The idea is to find the min depth of left / right child if exists. Recursive call to get there.

/**
 * 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;
        }
        if(root.left == null && root.right == null){
            return 1;
        }
       
        int leftDepth = Integer.MAX_VALUE;
        int rightDepth = Integer.MAX_VALUE;
        if(root.left != null){
            leftDepth = minDepth(root.left);
        }
        if(root.right != null){
            rightDepth = minDepth(root.right);
        }
 
        return leftDepth < rightDepth ? leftDepth + 1 : rightDepth + 1;
    }
}

没有评论: