Check Completeness Of A Binary Tree Problem
Description
LeetCode Problem 958.
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. It can have between 1 and 2^h nodes inclusive at the last level h.
Example 1:
Input: root = [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: root = [1,2,3,4,5,null,7]
Output: false
Explanation: The node with value 7 isn't as far left as possible.
Constraints:
- The number of nodes in the tree is in the range [1, 100].
- 1 <= Node.val <= 1000
Solution
Approach: Level-Order Traversal with Gaps
Write the tree level by level, left to right, and include a placeholder for every missing child. A tree is complete exactly when no real node comes after a missing one in that order: every level is filled from the left, and only the end of the last level may be empty.
Breadth-first search produces exactly this order:
- Start a queue with the root.
- Pop a node. If it is
null, remember that a gap has been seen. - If it is a real node and a gap was already seen, return
false. - Otherwise push both children, including
nullones, so the gaps take their place in the order. - If the queue empties without a problem, return
true.
The usual mistake is to push only the non-null children, as in a normal BFS. Then the gaps disappear: [1, 2, 3, null, 4] (node 2 has only a right child) would look like a full sequence 1, 2, 3, 4. With the gaps kept, the order is 1, 2, 3, null, 4, and the 4 after the null gives false.
Complexity: O(n) time and O(n) space for the queue, where n is the number of nodes.
import collections
class Solution:
def isCompleteTree(self, root: Optional[TreeNode]) -> bool:
queue = collections.deque([root])
seen_gap = False # have we met a missing child yet?
# Level order, keeping the missing children (None) in the queue as gaps.
while queue:
node = queue.popleft()
if node is None:
seen_gap = True
continue
if seen_gap:
return False # a real node after a gap: not as far left as possible
queue.append(node.left)
queue.append(node.right)
return True