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 2h
nodes inclusive at the last level h
.
Examples
Example 1:
graph TD 1 --- 2 & 3 2 --- 4 & 5 3 --- 6 3 ~~~ N1:::hidden classDef hidden display:none
|
|
Example 2:
graph TD 1 --- 2 & 3 2 --- 4 & 5 3 ~~~ N1:::hidden 3 --- 7 classDef hidden display:none
|
|
Solution
Method 1 - Using Level order Traversal
A complete binary tree satisfies two conditions:
- Every level, except possibly the last, is completely filled.
- All nodes at the last level are as far left as possible.
Here is the approach:
- Traverse the binary tree level by level using Breadth First Search (BFS) (i.e., a queue).
- While traversing, ensure that no
null
node comes before a non-null
node. If anull
node appears and there’s a non-null
node later, it is not a complete binary tree. - If the traversal ends without finding such irregularities, then the given binary tree is complete.
Code
|
|
|
|
Complexity
- Time:
O(n)
wheren
is the number of nodes, as we visit each node once during BFS traversal. - Space:
O(n)
for the queue used in BFS, as in the worst case, the last level nodes are stored in the queue.