https://leetcode.com/problems/check-completeness-of-a-binary-tree/
层次遍历,依次将每层的所有节点压入队列,空节点也照常压入,
每次从队列中取出一个节点,若该节点为空,则队列应该为空,或者剩余节点全部为空节点。
/**
* 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) {
if(root==nullptr) return true;
queue<TreeNode*> q;
q.push(root);
bool miss = false;
while(!q.empty()){
if(miss) return false;
TreeNode* tmp = q.front();
q.pop();
if(tmp!=nullptr){
q.push(tmp->left); //如果子节点是空,将null压入
q.push(tmp->right);
}
else{
miss=true;
while(!q.empty()){//当遇到一个节点是空时,队列里剩余节点必须全部是空
TreeNode* tmp = q.front();
q.pop();
if(tmp!=nullptr) return false;
}
}
}
return true;
}
};