Problem 455941 · medium · Phase 04 Non-Linear Data Structures

Is the Tree Complete?

binary trees · breadth-first search · completeness

A binary tree is complete if every level except possibly the last is entirely filled, and all nodes of the last level are packed as far left as possible. Given the root, return True if the tree is complete. An empty tree and a single node are complete.

Examples

      1
     / \
    2   3
   / \  /
  4   5 6

Input:  root = build_tree([1, 2, 3, 4, 5, 6])
Output: True
      1
     / \
    2   3
   /     \
  4       6

Input:  root = build_tree([1, 2, 3, 4, None, None, 6])
Output: False
Explanation: the last level has a hole between 4 and 6.

Constraints

  • 0 <= number of nodes <= 2000
  • Target complexity: O(n) time.

Goals

  • Enqueue missing children as None during a level-order walk
  • Detect a real node appearing after the first gap
  • Handle the empty tree and a single node
Starting Python…