Check Completeness of a Binary Tree - Problem

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.

Input & Output

Example 1 — Complete Binary Tree
$ Input: root = [1,2,3,4,5,6]
Output: true
💡 Note: All levels are filled completely, and the last level nodes (4,5,6) are as far left as possible. This satisfies the definition of a complete binary tree.
Example 2 — Incomplete Binary Tree
$ Input: root = [1,2,3,4,5,null,7]
Output: false
💡 Note: Node 7 exists but node 6 is missing. In a complete binary tree, all nodes in the last level must be as far left as possible, so there should be no gaps.
Example 3 — Single Node
$ Input: root = [1]
Output: true
💡 Note: A single node tree is always complete - it has only one level with one node, which satisfies all completeness conditions.

Constraints

  • The number of nodes in the tree is in the range [1, 100]
  • 1 ≤ Node.val ≤ 1000

Visualization

Tap to expand
Complete vs Incomplete Binary TreesComplete Tree ✓123456All nodes filled left-to-rightIncomplete Tree ✗123457gapNode 6 missing but 7 presentUse BFS to detect gaps in level-order traversalOnce null found, all remaining nodes must be null
Understanding the Visualization
1
Input
Binary tree in level-order representation
2
Check
Verify nodes are filled left-to-right with no gaps
3
Output
Return true if complete, false otherwise
Key Takeaway
🎯 Key Insight: In a complete binary tree, BFS will encounter all non-null nodes before any null nodes
Asked in
Facebook 15 Amazon 12 Microsoft 8
89.2K Views
Medium Frequency
~15 min Avg. Time
1.9K Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen