[LeetCode] Check Completeness of a Binary Tree

958. Check Completeness of a Binary Tree

Given the root of a binary tree, determine if it is a complete binary tree.

In a complete binary tree, every level, except possibly the last, is completely filled, and all nodes in the last level are as far left as possible. It can have between 1 and 2h nodes inclusive at the last level h.

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
/**
* 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);
while(!q.empty()) {
int sz = q.size();
bool eof = false;
while(sz--) {
auto n = q.front(); q.pop();
if(eof) {
if(n->left or n->right) return false;
} else {
if(n->left and n->right) {
q.push(n->left);
q.push(n->right);
} else if(n->left and !n->right) {
q.push(n->left);
eof = true;
} else if(!n->left and n->right) return false;
else eof = true;
}
}

if(eof) {
while(!q.empty()) {
auto n = q.front(); q.pop();
if(n->left or n->right) return false;
}
}
}
return true;
}
};

Author: Song Hayoung
Link: https://songhayoung.github.io/2022/06/02/PS/LeetCode/check-completeness-of-a-binary-tree/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.