[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 a binary tree node.
 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 == nullptr) return 0;
14         int left_min = minDepth(root->left);
15         int right_min = minDepth(root->right);
16         if (left_min == 0 && right_min == 0) {
17             return 1;
18         }
19         
20         if (left_min == 0) {
21             left_min = INT_MAX;
22         }
23         
24         if (right_min == 0) {
25             right_min = INT_MAX;
26         }
27         
28         return min(left_min, right_min) + 1;
29     }
30 };

 

posted @ 2015-12-17 22:27  skycore  阅读(158)  评论(0)    收藏  举报