Open
Description
Use BFS to do a level order traversal,
add childrens to the bfs queue,
until we met the first empty node.
For a complete binary tree,
there should not be any node after we met an empty one.
/**
* 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) {
queue<TreeNode*> q;
q.push(root);
while(!q.empty() && q.front() != nullptr){
auto front = q.front();
q.push(front->left);
q.push(front->right);
q.pop();
}
while(!q.empty() && q.front() == nullptr) q.pop();
return q.empty();
}
};
/**
* 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) {
queue<TreeNode*> q;
if(root == nullptr) return true;
bool f = false;
q.push(root);
while(!q.empty() && !f){
for(int i = 0, n = q.size(); i < n; i++){
auto top = q.front();
if(!f){
if(top->left && top->right){
q.push(top->left);
q.push(top->right);
} else if(!top->left && top->right){
return false;
} else {
if(top->left) q.push(top->left);
f = true;
}
} else {
if(top->left || top->right) return false;
}
q.pop();
}
}
for(int i =0, n = q.size(); i < n; i++){
auto top = q.front();
if(top->left || top->right) return false;
q.pop();
}
return true;
}
};