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.

 

Easy, DFS搞定

 1     public int minDepth(TreeNode root) {
 2         if(root == null)
 3         {
 4             return  0;
 5         }
 6         if(root.left == null &&  root.right == null){
 7             return  1;
 8         }
 9         int leftDepth=0;
10         int rightDepth = 0;
11         if(root.left !=null){
12             leftDepth = 1 + minDepth(root.left);
13         }
14         if(root.right !=null){
15             rightDepth = 1+ minDepth(root.right);
16         }
17         
18         if(leftDepth > 0){
19             if(rightDepth > 0)
20             {    return leftDepth<rightDepth ? leftDepth:rightDepth;}
21             else
22             {     return leftDepth;}
23         }else{
24             return rightDepth;
25         }
26     }

 

posted @ 2014-09-02 19:27  dijkstra-c  阅读(104)  评论(0编辑  收藏  举报