Check Completeness of a Binary Tree (LeetCode 958): Solution and Explanation
You get the root of a binary tree. Return true if it is complete, meaning every level is full except possibly the last, and the last level's nodes sit as far left as possible.
Intuition
Number the positions of a binary tree in level order: the root is position 1, the next level holds positions 2 and 3, then 4 to 7, and so on. A complete tree with n nodes uses exactly positions 1 to n and nothing else.
So the question becomes: walking the positions in level order, does an empty position ever come before a real node? If it does, there is a hole inside the tree and it is not complete.
A breadth-first search walks positions in exactly that order, as long as it also enqueues the null children. The first null it dequeues opens the gap, and any real node dequeued after that proves the tree is incomplete.
Approach: BFS with null markers
- Put the root on a queue and set
seen_null = false. - Dequeue the next item. If it is null, set
seen_null = trueand continue. - If it is a real node and
seen_nullis already true, a node follows a gap: return false. - Otherwise enqueue its left and right children, including nulls, so every position takes a turn.
- When the queue is empty, no node followed a gap: return true.
Step-by-step example
root = [1,2,3,4,5,6]
- Queue = [1]. Dequeue 1 (slot 1) and enqueue 2 and 3.
- Dequeue 2 (slot 2), enqueue 4 and 5. Dequeue 3 (slot 3), enqueue 6 and null.
- Dequeue 4, 5 and 6 (slots 4 to 6). Each is a leaf, so each enqueues two nulls.
- Dequeue the null in slot 7: seen_null becomes true. Every item left in the queue is also null.
- The queue drains with no real node after the gap, so return true.
Code: Python, Java, C++
1class Solution:
2 def isCompleteTree(self, root: Optional[TreeNode]) -> bool:
3 queue = collections.deque([root])
4 seen_null = False
5 while queue:
6 node = queue.popleft()
7 if node is None:
8 seen_null = True
9 elif seen_null:
10 return False
11 else:
12 queue.append(node.left)
13 queue.append(node.right)
14 return True1class Solution {
2 public boolean isCompleteTree(TreeNode root) {
3 Queue<TreeNode> queue = new LinkedList<>();
4 queue.offer(root);
5 boolean seenNull = false;
6 while (!queue.isEmpty()) {
7 TreeNode node = queue.poll();
8 if (node == null) {
9 seenNull = true;
10 } else if (seenNull) {
11 return false;
12 } else {
13 queue.offer(node.left);
14 queue.offer(node.right);
15 }
16 }
17 return true;
18 }
19}1class Solution {
2public:
3 bool isCompleteTree(TreeNode* root) {
4 queue<TreeNode*> q;
5 q.push(root);
6 bool seenNull = false;
7 while (!q.empty()) {
8 TreeNode* node = q.front();
9 q.pop();
10 if (node == nullptr) {
11 seenNull = true;
12 } else if (seenNull) {
13 return false;
14 } else {
15 q.push(node->left);
16 q.push(node->right);
17 }
18 }
19 return true;
20 }
21};Time and space complexity
O(n)
Each node is enqueued and dequeued once, and each node adds two children (some null), so the queue sees at most 2n + 1 items.
O(n)
The queue can hold a whole level plus its null children, which is O(n) for a wide tree.
Other approaches
Index counting with DFS (time O(n), space O(h))
Count the nodes n, then run a DFS that gives each node its level-order index (children of i are 2i and 2i+1). The tree is complete exactly when no index exceeds n.
BFS with explicit indices (time O(n), space O(n))
Store (node, index) pairs in the queue and check that the k-th dequeued node has index k. This skips enqueuing nulls but needs the index bookkeeping.
Common mistakes
- Skipping null children in the BFS. Without them the walk cannot see the holes, and every tree looks complete.
- Only checking that every internal node has two children. A tree whose last level is filled from the right, such as [1,2,3,null,4], passes that kind of check but is not complete.
- Using a queue type that refuses nulls, such as Java's ArrayDeque. LinkedList accepts them.
- Stopping at the first null. The gap only matters if a real node shows up after it, so keep draining the queue.
Frequently asked questions
Why does a null followed by a node mean the tree is incomplete?
BFS dequeues positions in level order. A null at position k followed by a node at a later position means position k is empty while a later one is filled, which breaks the left-packed rule.
Is a perfect tree complete?
Yes. Every level is full, so the nodes use positions 1 to n with no gaps.
How is this different from a full binary tree?
A full binary tree means every node has zero or two children. Completeness is about where nodes sit, not how many children they have; [1,2,3,4] is complete but not full.
Can I stop as soon as I see a null?
Not immediately. You still need to confirm that no real node remains in the queue. A simple way is to keep the loop and fail on the first real node after the gap.