Check Completeness of a Binary Tree
Explanation & Solution
Description
Given the root of a binary tree, determine if it is a complete binary tree.
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. The last level can have between 1 and 2ʰ nodes inclusive, where h is the height of the tree.
Examples
Example 1:
```tree
[1, 2, 3, 4, 5, 6]
`
Output: true
Explanation: Every level before the last is full, and all nodes in the last level are as far left as possible.
Example 2:
```tree
[1, 2, 3, 4, 5, null, 7]
`
Output: false
Explanation: Node 7 is on the right side of level 2, but the position to its left (node 3's left child) is empty. This violates the completeness property.
Example 3:
```tree
[1]
`
Output: true
Constraints
- The number of nodes in the tree is in the range
[1, 100] 1 <= Node.val <= 1000
Approach
Tree Breadth-First Search pattern
1. Handle Empty Tree
- If
rootisnull, returntrue(an empty tree is trivially complete)
2. Initialize BFS
- Create a queue initialized with the root node
- Track a boolean
seenNull— whether we've encountered a null node yet
3. BFS with Null Detection
- Process nodes from the queue one at a time:
- If the current node is
null: - Set
seenNull = true - If the current node is not null:
- If
seenNullis alreadytrue, returnfalse— a non-null node after a gap means the tree is not complete - Otherwise, push both
node.leftandnode.rightinto the queue (even if they are null)
4. Return True
- If BFS completes without finding a non-null node after a null, the tree is complete
Key Insight
- In a complete binary tree, when we do BFS (level order), all null nodes must come after all non-null nodes
- The moment we see a null, every subsequent node must also be null
- If we ever see a non-null node after a null, the tree is not complete
Visualization
Press play to start DFS traversal