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
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class Solution {
public:
int minDepth(TreeNode* root) {
int ret = 0;
if (root == nullptr)
return 0;

if (root->left) {
if (root->right) {
ret = min(minDepth(root->left), minDepth(root->right)) + 1;
} else {
ret = minDepth(root->left) + 1;
}
} else if (root->right) {
ret = minDepth(root->right) + 1;
} else {
return 1;
}

return ret;
}
};