[leedcode 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 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) {
        //注意考虑节点只有一个子节点是空的情况,此时应该舍弃空子树,一种方法,将其设为最大值,一种直接舍弃
   /*     if(root==null) return 0;

        if(root.left==null&&root.right==null) return 1;


        if(root.left==null) return minDepth(root.right)+1;
        if(root.right==null) return minDepth(root.left)+1;
        return Math.min(minDepth(root.left),minDepth(root.right))+1;*/
        
        
        if(root==null) return 0;
        int left=minDepth(root.left);
        int right=minDepth(root.right);
        if(root.left==null&&root.right==null) return 1;//root.left==null等价于left==0
        if(left==0) left=Integer.MAX_VALUE;
        if(right==0) right=Integer.MAX_VALUE;
        return Math.min(left,right)+1;
    }
}

 

posted @ 2015-07-22 13:10  ~每天进步一点点~  阅读(141)  评论(0编辑  收藏  举报