Description:
题目大意:判断是不是完全二叉树
解题思路:
算法标签:BFS
- 完全二叉树的空节点在最后结尾处
- 进行层序遍历,如果未到结尾处就访问到空节点,则不是完全二叉树
代码:
/*
* struct TreeNode {
* int val;
* struct TreeNode *left;
* struct TreeNode *right;
* TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
* };
*/
class Solution {
public:
bool isCompleteTree(TreeNode* root) {
if(root == NULL)
return true;
// 层序遍历如果未访问完就有空节点,就不是完全二叉树
queue<TreeNode* >tree;
tree.push(root);
// 标记空节点
bool flag = false;
while(!tree.empty()) {
int size = tree.size();
for(int i = 0;i < size;i++) {
TreeNode* node = tree.front();
tree.pop();
if(flag && node != NULL)
return false;
if(node == NULL)
flag = true;
else {
tree.push(node -> left);
tree.push(node -> right);
}
}
}
return true;
}
};