Check Completeness of a Binary Tree

IF
AlgoAxiomStaff Engineers
JSTS
Medium20 mins

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. The last level can have between 1 and nodes inclusive, where h is the height of the tree.

Examples

Example 1:

123456

Input: root = [1, 2, 3, 4, 5, 6]

Output: true

Explanation: Every level before the last is full, and all nodes in the last level are as far left as possible.

Example 2:

123457

Input: root = [1, 2, 3, 4, 5, null, 7]

Output: false

Explanation: Node 7 is on the right side of level 2, but the position to its left (node 3's left child) is empty. This violates the completeness property.

Example 3:

1

Input: root = [1]

Output: true

Constraints

  • The number of nodes in the tree is in the range [1, 100]
  • 1 <= Node.val <= 1000
Source: Tree Breadth-First Search pattern — AlgoAxiom
JavaScript
Test Case 1
root = [1, 2, 3]
Test Case 2
root = [1, 2, 3, 4, 5]
Idle