Left-Packed Tree Check from a Level-Order Array
Trees & GraphsAuto-graded · 24 test casesLast 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.
Nonemarks a missing child of a node that exists.- Children of missing nodes are not listed at all.
- Trailing
Nonevalues 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 returnTrue.
Constraints
- The number of nodes in the tree is between
0and100. - 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.
Worked solution
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach
The solution has two phases.
Phase 1: rebuild the tree. Create the root from the first entry (or return True if the list is empty or starts with None). Keep a queue of nodes that still need children. For each such node, take the next list entry as its left child and the following entry as its right child, creating a node when the entry is not None and adding it to the queue. Stop when the queue is empty or the list is exhausted. Leftover entries are ignored, and positions beyond the end of the list are treated as absent.
Phase 2: check completeness. Run a breadth-first traversal from the root. For each dequeued node, inspect its left and right child slots in order:
- If the slot is empty, set a flag
gap_seen. - If the slot holds a node and
gap_seenis already set, returnFalse. - Otherwise enqueue the child.
If the traversal finishes without a violation, return True.
Why it is correct
Number positions in a perfect binary tree in breadth-first order: the root is 1 and the children of position i are 2i and 2i+1. A tree with n nodes is complete exactly when its nodes occupy positions 1..n with no holes.
The BFS over child slots visits positions in increasing order.
- In a complete tree, occupied positions form a prefix, so after the first empty slot every later slot is empty. No node ever follows a gap, and we return
True. - If a node follows a gap, the occupied positions are not a contiguous prefix, so the tree is not complete. Returning
Falseis right.
Empty slots have no children, so nothing is enqueued beneath them. Any positions below a gap are also gaps and come later in the order, so this does not hide violations.
Complexity
- Time: O(N), where N is the length of the list. Each entry is consumed once when building, and each node is dequeued once during the BFS.
- Space: O(N) for the rebuilt tree and the queues.
Reference solution
from collections import deque
from typing import List, Optional
class _Node:
def __init__(self, val):
self.val = val
self.left = None
self.right = None
def is_left_packed(level_order: List[Optional[int]]) -> bool:
if not level_order or level_order[0] is None:
return True
n = len(level_order)
root = _Node(level_order[0])
waiting = deque([root])
idx = 1
while waiting and idx < n:
parent = waiting.popleft()
if idx < n and level_order[idx] is not None:
parent.left = _Node(level_order[idx])
waiting.append(parent.left)
idx += 1
if idx < n and level_order[idx] is not None:
parent.right = _Node(level_order[idx])
waiting.append(parent.right)
idx += 1
queue = deque([root])
gap_seen = False
while queue:
node = queue.popleft()
for child in (node.left, node.right):
if child is None:
gap_seen = True
else:
if gap_seen:
return False
queue.append(child)
return True