Verify BST Property on a Level-Order Encoded Tree
Trees & GraphsAuto-graded · 24 test casesLast updated
Test whether a breadth-first list representation of a binary tree satisfies strict BST ordering without allowing duplicate values.
Task
You are given a binary tree encoded as a breadth-first (level-order) list. Your job is to determine whether the tree satisfies the strict binary-search-tree invariant: for every node, all values in its left subtree are strictly less than the node's value, and all values in its right subtree are strictly greater. Duplicate values anywhere in the tree make it invalid.
Implement:
def validate_bst(tree: list[int | None]) -> bool:
...
Input Encoding
The tree is represented as a list of integers and None values rather than node objects, so it can be expressed as a JSON literal.
- The first element is the root. An empty list, or any list whose root slot is
None, represents an empty tree. - Child slots are filled breadth-first: the next two list entries after a node are its left child, then its right child. A
Noneentry means that child does not exist and consumes no further child slots of its own. - If the list ends before all child slots are filled, the remaining children are treated as missing.
- Trailing
Noneentries have no effect. Inputs are guaranteed to be well-formed: no non-Nonevalue will appear without a parent to claim it. - Example:
[1, None, 2, 3]means root 1 with no left child, a right child 2, and node 2 has a left child 3.
Constraints
- At most 100,000 non-
Nonenodes in the encoding. - Values are signed integers that may equal the minimum or maximum value of the caller's integer type.
- The structure is a proper tree with no cycles or shared children.
- The tree may be fully skewed (all left children or all right children).
- Avoid numeric sentinels or arithmetic like
value - 1that can misbehave at integer boundaries. - Empty trees return
True. Duplicates returnFalse.
Examples
Example 1
Input: validate_bst([2, 1, 3])
Output: True
Example 2
Input: validate_bst([8, 3, 10, None, None, 6])
Output: False
Example 3
Input: validate_bst([2, 2, 3])
Output: False
Hints
Hint 1
The BST property is not just local to parent-child pairs. Track the full allowed value range inherited from all ancestors, not just the immediate parent.
Hint 2
Use None for unbounded bounds instead of fixed sentinels like INT_MIN or INT_MAX, since real values can equal those extremes.
Hint 3
Processing nodes in breadth-first order lets you parse the input list and validate intervals in a single pass, avoiding a separate tree-building step.
Worked solution
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach
Every node must fall within an open interval (lo, hi) inherited from its ancestors. The root has no bounds (represented as None). When moving to a left child, the upper bound tightens to the parent's value. When moving to a right child, the lower bound tightens to the parent's value. A node is invalid if its value is less than or equal to the lower bound, or greater than or equal to the upper bound.
The input list is already in breadth-first order, so we can parse and validate in a single pass. A queue processes nodes in the same order they appear in the list. Each queue entry carries the node's value alongside its (lo, hi) interval. An index pointer walks forward through the list to assign left and right children to each dequeued node.
Using None for unbounded limits avoids sentinel values that could collide with real input values at the integer extremes. Strict comparisons (<= and >=) reject duplicates, satisfying the strict BST invariant.
Why It Is Correct
The interval (lo, hi) at any node captures every ancestor constraint along the path from the root. For a node deep in the left subtree of a right subtree, lo comes from the nearest ancestor where the path went right, and hi comes from the nearest ancestor where the path went left. Each step down only narrows the interval, never widens it. So if any ancestor's constraint would be violated, the current interval already reflects it.
Duplicates fail because the comparisons are strict: if a child equals its parent, the bound set by that parent catches it. For example, a left child equal to its parent triggers val >= hi where hi is the parent's value.
Complexity
- Time: O(n) where n is the number of non-
Nonenodes. Each node is enqueued and dequeued exactly once, and the index pointer advances linearly through the list. - Space: O(n) for the queue in the worst case (a complete tree has roughly n/2 nodes at the deepest level). No recursion is used, so there is no call-stack risk on skewed trees of 100,000 nodes.
Reference Solution
from collections import deque
def validate_bst(tree: list[int | None]) -> bool:
if not tree or tree[0] is None:
return True
# Queue entries: (value, lower_bound, upper_bound)
# None for a bound means that side is unbounded.
queue = deque()
queue.append((tree[0], None, None))
idx = 1
while queue:
val, lo, hi = queue.popleft()
if lo is not None and val <= lo:
return False
if hi is not None and val >= hi:
return False
# Assign left child from the input list
if idx < len(tree):
left_val = tree[idx]
idx += 1
if left_val is not None:
queue.append((left_val, lo, val))
# Assign right child from the input list
if idx < len(tree):
right_val = tree[idx]
idx += 1
if right_val is not None:
queue.append((right_val, val, hi))
return True