KatInterview

Left-Packed Tree Check from a Level-Order Array

Trees & GraphsAuto-graded · 24 test cases
MediumAuto-gradedTrees & Graphsbinary-treebfslevel-order

Last updated

Decide whether a binary tree given as a level-order array with None placeholders is complete, by rebuilding it and scanning breadth-first for a node that follows a gap.

Left-Packed Tree Check

A binary tree is called left-packed (also known as a complete binary tree) when every level except possibly the deepest one is entirely full, and the nodes on the deepest level sit as far to the left as they can.

You are given a binary tree serialized in level order. Write a function that returns True if the tree is left-packed and False otherwise.

Input format

The parameter level_order is a list whose entries are integers or None:

  • Nodes are listed breadth-first, level by level, from left to right.
  • None marks a missing child of a node that exists.
  • Children of missing nodes are not listed at all.
  • Trailing None values may be omitted.

To reconstruct the tree, process existing nodes in breadth-first order. Each one consumes the next entry as its left child and the entry after that as its right child. A None entry means that child is absent. Once every existing node has been given its two child slots, any remaining entries in the list are ignored. Entries past the end of the list count as absent.

Output

Return a boolean: True if the tree is complete, False otherwise.

Special cases

  • An empty list, or a list whose first entry is None, represents an empty tree. An empty tree is complete, so return True.

Constraints

  • The number of nodes in the tree is between 0 and 100.
  • Node values are integers.
  • The list follows the serialization rules above.

Examples

Example 1

Input: is_left_packed([1, 2, 3, 4, 5, 6])

Output: True

Example 2

Input: is_left_packed([1, 2, 3, 4, 5, None, 7])

Output: False

Hints

Hint 1

Rebuild the tree first: keep a queue of nodes still waiting for children, and hand each one the next two entries of the list.

Hint 2

Traverse the rebuilt tree breadth-first and look at every child slot, including empty ones, in left-to-right order.

Hint 3

Once you have seen one empty slot, no real node may appear later in that order. Keep a single boolean flag and return False the moment a real node shows up after it is set.