0%

958. 二叉树的完全性检验

958. 二叉树的完全性检验

层序遍历
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
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode() : val(0), left(nullptr), right(nullptr) {}
* TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
* TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
* };
*/
class Solution {
public:
bool isCompleteTree(TreeNode* root) {
queue<TreeNode*> q;
q.push(root);
int expect = 1;
while(!q.empty())
{
int sz = q.size();
if(sz != expect)
break;
expect <<= 1;
bool broke = false;
for(int i = 0; i < sz; ++i)
{
auto p = q.front();
q.pop();
if(broke && (p->left || p->right)) // 前面断裂了,如果下一层还不是最后一层,那没了啊
return false;
if(!p->left && p->right)
return false;
if(!p->right) // 出现了断层,如果不是最后一层,那你g了
broke = true;
if(p->left)
q.push(p->left);
if(p->right)
q.push(p->right);
}
}
while(!q.empty())
{
auto p = q.front();
q.pop();
if(p->left || p->right)
return false;
}
return true;
}
};

也算是层序

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
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode() : val(0), left(nullptr), right(nullptr) {}
* TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
* TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
* };
*/
class Solution {
public:
bool isCompleteTree(TreeNode* root) {
queue<TreeNode*> q;
int i = 1;
q.push(root);
bool isBlock = false;
while(!q.empty())
{
auto p = q.front();
q.pop();
if(!p)
{
isBlock = true;
continue;
}
if(isBlock)
return false;
q.push(p->left);
q.push(p->right);
}
return true;
}
};