forked from kamyu104/LeetCode-Solutions
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathcheck-completeness-of-a-binary-tree.cpp
58 lines (56 loc) · 1.59 KB
/
check-completeness-of-a-binary-tree.cpp
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
51
52
53
54
55
56
57
58
// Time: O(n)
// Space: O(w)
/**
* 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:
bool isCompleteTree(TreeNode* root) {
bool end = false;
vector<TreeNode*> current{root};
while (current.empty() == false) {
vector<TreeNode*> next_level;
for (const auto& node : current) {
if (!node) {
end = true;
continue;
}
if (end) {
return false;
}
next_level.emplace_back(node->left);
next_level.emplace_back(node->right);
}
current = move(next_level);
}
return true;
}
};
// Time: O(n)
// Space: O(w)
class Solution2 {
public:
bool isCompleteTree(TreeNode* root) {
vector<pair<TreeNode*, int>> prev_level, current{{root, 1}};
int count = 0;
while (current.empty() == false) {
count += current.size();
vector<pair<TreeNode*, int>> next_level;
for (const auto& node : current) {
if (node.first) {
next_level.emplace_back(node.first->left, 2 * node.second);
next_level.emplace_back(node.first->right, 2 * node.second + 1);
}
}
prev_level = move(current);
current = move(next_level);
}
return prev_level.back().second == count;
}
};