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
Check Completeness of a Binary Tree INPUT Binary Tree Structure: 1 2 3 4 5 6 Input Array: root = [1,2,3,4,5,6] L0 L1 L2 ALGORITHM (BFS) 1 Initialize Queue Add root to queue 2 BFS Traversal Process level by level 3 Track Null Nodes Set flag when null found 4 Validate No node after null Queue Processing: 1 2 3 4 5 6 BFS Order: 1 --> 2 --> 3 --> 4 --> 5 --> 6 nullFound = false (no gaps!) FINAL RESULT Complete Binary Tree: 1 2 3 4 5 6 OK - Complete Output: true All nodes left-aligned Key Insight: A complete binary tree has no gaps when traversed level by level using BFS. If we encounter a null node, all subsequent nodes must also be null. The BFS approach processes nodes in level order, making it easy to detect any non-null node appearing after a null, which would indicate an incomplete tree. TutorialsPoint - Check Completeness of a Binary Tree | BFS Approach
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