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

解法:参照http://blog.csdn.net/sbitswc/article/details/26526031

 1 /**
 2  * Definition for binary tree
 3  * struct TreeNode {
 4  *     int val;
 5  *     TreeNode *left;
 6  *     TreeNode *right;
 7  *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
 8  * };
 9  */
10 class Solution {
11 public:
12     int minDepth(TreeNode *root) {
13         if (root == NULL) return 0;
14         
15         int left_depth = minDepth(root->left);
16         int right_depth = minDepth(root->right);
17     
18         if (left_depth == 0 && right_depth == 0)
19             return 1;
20         if (left_depth == 0)
21             left_depth = INT_MAX;
22         if (right_depth == 0)
23             right_depth = INT_MAX;
24             
25         return min(left_depth, right_depth) + 1;
26     }
27 };

 

posted @ 2015-02-26 20:54  vincently  阅读(170)  评论(0编辑  收藏  举报