leetcode -- 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.

 

 1 /**
 2  * Definition for binary tree
 3  * public class TreeNode {
 4  *     int val;
 5  *     TreeNode left;
 6  *     TreeNode right;
 7  *     TreeNode(int x) { val = x; }
 8  * }
 9  */
10 public class Solution {
11     public int minDepth(TreeNode root) {
12         // Start typing your Java solution below
13         // DO NOT write main() function
14         if(root == null){
15             return 0;
16         }
17         int left = 0, right = 0;
18         if(root.left != null){
19             left = minDepth(root.left);
20         }
21         
22         if(root.right != null){
23             right = minDepth(root.right);
24         }
25         
26         if(root.left != null && root.right != null)
27             return 1 + Math.min(left, right);
28         else if(root.left == null && root.right != null){
29             return 1 + right;
30         } else if(root.left != null && root.right == null){
31             return 1 + left;
32         } else {
33             return 1;
34         }
35         
36     }
37 }

 

posted @ 2013-08-14 23:10  feiling  阅读(289)  评论(0编辑  收藏  举报