Leetcode-Minimum Depth of Binary Tree

LiBlog發表於2014-11-08

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.

 

Solution:

 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         if (root==null) return 0;
13         int res = minDepthRecur(root,0);
14         return res;
15     }
16     
17     public int minDepthRecur(TreeNode curNode, int curDepth){
18         if (curNode.left==null&&curNode.right==null){
19             return curDepth+1;
20         }
21         
22         int left = Integer.MAX_VALUE;
23         int right = Integer.MAX_VALUE;
24         if (curNode.left!=null)
25             left = minDepthRecur(curNode.left, curDepth+1);
26         if (curNode.right!=null)
27             right = minDepthRecur(curNode.right,curDepth+1);
28         
29         if (left<right)
30             return left;
31         else
32             return right;
33     }
34 }

This is a easy recursive problem.

相關文章