Check Completeness of a Binary Tree - Problem
Complete Binary Tree Verification
You're given the
A complete binary tree is a special type of binary tree where:
• Every level is completely filled, except possibly the last level
• All nodes in the last level are positioned as far left as possible
• The last level can have between
Goal: Return
Example: A tree with nodes [1,2,3,4,5,6] is complete, but [1,2,3,4,null,6] is not (gap in last level).
You're given the
root of a binary tree and need to determine if it represents a complete binary tree.A complete binary tree is a special type of binary tree where:
• Every level is completely filled, except possibly the last level
• All nodes in the last level are positioned as far left as possible
• The last level can have between
1 and 2h nodes (where h is the height)Goal: Return
true if the tree is complete, false otherwise.Example: A tree with nodes [1,2,3,4,5,6] is complete, but [1,2,3,4,null,6] is not (gap in last level).
Input & Output
example_1.py — Complete Binary Tree
$
Input:
[1,2,3,4,5,6]
›
Output:
true
💡 Note:
This tree is complete because all levels are filled from left to right. Level 0 has node 1, level 1 has nodes 2,3, and level 2 has nodes 4,5,6 positioned leftmost.
example_2.py — Incomplete Binary Tree
$
Input:
[1,2,3,4,5,null,7]
›
Output:
false
💡 Note:
This tree is not complete because there's a gap in the last level. Node 6 is missing, but node 7 exists, violating the 'leftmost' rule for complete binary trees.
example_3.py — Single Node Tree
$
Input:
[1]
›
Output:
true
💡 Note:
A single node tree is always complete by definition, as there are no gaps or violations of the completeness property.
Constraints
- The number of nodes in the tree is in the range [0, 100]
- 1 ≤ Node.val ≤ 1000
- Note: Tree is given in level-order array format where null represents missing nodes
Visualization
Tap to expand
Understanding the Visualization
1
Complete Tree Pattern
All levels filled left-to-right, no gaps in last level
2
Incomplete Tree Pattern
Gap exists in last level with nodes to the right of the gap
3
BFS Detection Method
Level-order traversal catches violations immediately
Key Takeaway
🎯 Key Insight: BFS level-order traversal naturally detects completeness violations - once we see a null node, all subsequent nodes in the queue must also be null for the tree to be complete.
💡
Explanation
AI Ready
💡 Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code