-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathcompletebinarytree.cpp
61 lines (59 loc) · 1.51 KB
/
completebinarytree.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
59
60
61
/**
* 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 Pow2(int n, int exp) {
while (exp > 0) {
exp--;
n /= 2;
}
return n == 1 ? true : false;
}
bool isCompleteTree(TreeNode* root) {
vector<vector<int> >X;
queue<TreeNode*> Q;
TreeNode *curr;
bool flag = true;
Q.push(root);
int i,s;
while (!Q.empty()) {
vector<int> level;
flag = true;
s = Q.size();
for (i = 0; i < s; i++) {
curr = Q.front();
Q.pop();
level.push_back(curr->val);
if (curr->left != NULL) {
if (flag)
Q.push(curr->left);
else
return false;
}
else
flag = false;
if (curr->right != NULL) {
if (flag)
Q.push(curr->right);
else
return false;
}
else
flag = false;
}
X.push_back(level);
}
for (i = 1; i < X.size()-1; i++) {
if (!Pow2(X[i].size(),i))
return false;
}
return true;
}
};