-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathlc_0111.cpp
More file actions
50 lines (48 loc) · 1.11 KB
/
lc_0111.cpp
File metadata and controls
50 lines (48 loc) · 1.11 KB
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
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
/**
* @file lc_0111.cpp
* @brief https://leetcode-cn.com/problems/minimum-depth-of-binary-tree/
* @author YongDu
* @date 2021-09-09
*/
class Solution {
public:
int minDepth(TreeNode *root) {
if (root == nullptr) {
return 0;
}
if (root->left != nullptr && root->right != nullptr) {
return std::min(minDepth(root->left), minDepth(root->right)) + 1;
}
return std::max(minDepth(root->left), minDepth(root->right)) + 1;
}
};
// 层序遍历版
class Solution {
public:
int minDepth(TreeNode *root) {
if (nullptr == root) {
return 0;
}
int depth = 0;
std::queue<TreeNode *> que;
que.push(root);
while (!que.empty()) {
int size = que.size();
depth++;
while (size--) {
TreeNode *node = que.front();
que.pop();
if (!node->left && !node->right) { // 当左右孩子皆为空,到达最小深度
return depth;
}
if (node->left) {
que.emplace(node->left);
}
if (node->right) {
que.emplace(node->right);
}
}
}
return depth;
}
};