# 958. Check Completeness of a Binary Tree

Given a binary tree, determine if it is a  complete binary tree.

Definition of a complete binary tree from Wikipedia:
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.

Example 1:

``````Input: [1,2,3,4,5,6]
Output: true
Explanation: Every level before the last is full (ie. levels with node-values {1} and {2, 3}), and all nodes in the last level ({4, 5, 6}) are as far left as possible.
``````

Example 2:

``````Input: [1,2,3,4,5,null,7]
Output: false
Explanation: The node with value 7 isn't as far left as possible.
``````

Note:

1. The tree will have between 1 and 100 nodes.

``````class Solution {
public:
bool isCompleteTree(TreeNode* root) {
queue<TreeNode*> q{{root}};
while (q.front() != NULL) {
TreeNode *cur = q.front(); q.pop();
q.push(cur->left);
q.push(cur->right);
}
while (!q.empty() && q.front() == NULL) {
q.pop();
}
return q.empty();
}
};
``````

``````class Solution {
public:
bool isCompleteTree(TreeNode* root) {
queue<TreeNode*> q{{root}};
bool found = false;
while (!q.empty()) {
TreeNode *cur = q.front(); q.pop();
if (!cur) {
found = true;
} else {
if (found) return false;
q.push(cur->left);
q.push(cur->right);
}
}
return true;
}
};
``````

Github 同步地址:

https://github.com/grandyang/leetcode/issues/958

https://leetcode.com/problems/check-completeness-of-a-binary-tree/

https://leetcode.com/problems/check-completeness-of-a-binary-tree/discuss/205682/JavaC%2B%2BPython-BFS-Level-Order-Traversal

https://leetcode.com/problems/check-completeness-of-a-binary-tree/discuss/205768/Java-easy-Level-Order-Traversal-one-while-loop

LeetCode All in One 题目讲解汇总(持续更新中…)

 微信打赏 Venmo 打赏
（欢迎加入博主的知识星球，博主将及时答疑解惑，并分享刷题经验与总结，试运营期间前五十位可享受半价优惠～）

×

Help us with donation