KatInterview

Verify BST Property on a Level-Order Encoded Tree

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

Last 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 None entry 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 None entries have no effect. Inputs are guaranteed to be well-formed: no non-None value 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-None nodes 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 - 1 that can misbehave at integer boundaries.
  • Empty trees return True. Duplicates return False.

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.