Skip to contentKEEP THE CRAFTTHE SANCTUARY

Binary Search Tree

A BST preserves an ordering interval for every subtree, inherited from all ancestors. Search discards one side per comparison, validation carries strict bounds, and time depends on height rather than an automatic logarithmic guarantee.

1 practice exercise4 interview problems

Recognize it when A binary tree promises ordered subtrees or must be checked for that promise.

Checking your account…

Binary Search Tree Code Labs

Mental Model

A binary search tree adds order to binary-tree shape. Under a strict no-duplicates policy, every value in a node’s left subtree is smaller and every value in its right subtree is larger. This is a global ancestor constraint, not merely a comparison with each immediate child.

Ordering Is a Global Invariant

Each descent narrows an allowed interval. Going left replaces the upper bound with the current value; going right replaces the lower bound. A descendant must satisfy every bound inherited from all ancestors. Inorder traversal visits a valid BST in sorted order, but sorted output alone does not identify the original shape.

Build and Query by Comparison

Search and insertion compare once per visited level, discarding the impossible subtree. Their cost is O(h), where h is tree height: O(log n) when balanced and O(n) for a chain created by sorted insertions. Python does not provide a built-in mutable BST; the bisect module(opens in a new tab) serves sorted lists and has different insertion costs.

Build and Query a BST

Reference
def bst_operations(values, queries):
    root = None
    for value in values:
        if root is None:
            root = [value, None, None]
            continue
        node = root
        while True:
            if value == node[0]:
                break
            side = 1 if value < node[0] else 2
            if node[side] is None:
                node[side] = [value, None, None]
                break
            node = node[side]
    ordered = []
    def visit(node):
        if node is not None:
            visit(node[1])
            ordered.append(node[0])
            visit(node[2])
    visit(root)
    found = []
    for query in queries:
        node = root
        while node is not None and node[0] != query:
            node = node[1] if query < node[0] else node[2]
        found.append(node is not None)
    return [ordered, found]
Practice

Implement bst_operations(values, queries). Insert unique values, then return inorder values and directed-search results.

Public tests

  • Verify insertion and directed queries

Loading interactive editor.If it does not appear, the reference and starter code remain readable.Reload editor

Build and Query a BST

def bst_operations(values, queries):
    root = None
    for value in values:
        if root is None:
            root = [value, None, None]
            continue
        node = root
        while True:
            if value == node[0]:
                break
            side = 1 if value < node[0] else 2
            if node[side] is None:
                node[side] = [value, None, None]
                break
            node = node[side]
    ordered = []
    def visit(node):
        if node is not None:
            visit(node[1])
            ordered.append(node[0])
            visit(node[2])
    visit(root)
    found = []
    for query in queries:
        node = root
        while node is not None and node[0] != query:
            node = node[1] if query < node[0] else node[2]
        found.append(node is not None)
    return [ordered, found]

Validate with Ancestor Bounds

Checking left < node < right for immediate children misses a value that violates a higher ancestor. Pass lower and upper bounds through recursion. Decide duplicate policy explicitly; the strict contract uses open bounds, so equality is invalid anywhere.

Validate Ancestor Bounds

Reference
def is_valid_bst(level_order):
    def valid(index, lower, upper):
        if index >= len(level_order) or level_order[index] is None:
            return True
        value = level_order[index]
        if not lower < value < upper:
            return False
        return valid(2 * index + 1, lower, value) and valid(2 * index + 2, value, upper)
    return valid(0, float('-inf'), float('inf'))
Practice

Implement is_valid_bst(level_order) for a complete-index array. Require strict ordering against all ancestor lower and upper bounds.

Public tests

  • Reject nonlocal ordering violation

Loading interactive editor.If it does not appear, the reference and starter code remain readable.Reload editor

Validate Ancestor Bounds

def is_valid_bst(level_order):
    def valid(index, lower, upper):
        if index >= len(level_order) or level_order[index] is None:
            return True
        value = level_order[index]
        if not lower < value < upper:
            return False
        return valid(2 * index + 1, lower, value) and valid(2 * index + 2, value, upper)
    return valid(0, float('-inf'), float('inf'))

Trace a Descendant Against Its Ancestor Interval

The actual validation Lab receives [8, 3, 12, None, None, 6, 14]. Value 6 is a valid local left child of 12, but it belongs to root 8’s right subtree and therefore must also be greater than 8.

print(is_valid_bst([8, 3, 12, None, None, 6, 14])) followed by print(is_valid_bst([8, 3, 12, None, None, 10, 14]))

Step Executed statement State Why
1 valid(0, float('-inf'), float('inf')) index = 0; value = 8; interval = (-inf, inf) The root initially has no finite ancestor constraints.
2 valid(2 * index + 1, lower, value) index = 1; value = 3; interval = (-inf, 8) A left descent tightens the upper bound to the root.
3 valid(2 * index + 2, value, upper) index = 2; value = 12; interval = (8, inf) The right subtree inherits a strict lower bound of 8.
4 valid(2 * index + 1, lower, value) index = 5; value = 6; interval = (8, 12) The left child of 12 keeps the root’s lower bound.
5 if not lower < value < upper: return False 8 < 6 < 12 is False; validation returns False Short-circuit propagation rejects the complete tree; replacing 6 with 10 satisfies both ancestors.
Print Output
1 False
2 True

A subtree inherits the ancestor interval even when its immediate parent changes. The failed lower bound is the proof of invalidity; merely comparing 6 with 12 would accept the wrong structure.

Use a BST when the input is already a tree or dynamic ordered operations are central. Use binary search on a sorted list for compact static data and frequent reads; insertion into the middle still costs O(n). Use a hash map for exact-key lookup without range or order queries, and a heap when only the current extreme matters.

BST Ordering and Height Mistakes

  • Validating only parent-child pairs ignores ancestor bounds.
  • Claiming O(log n) without a balance guarantee hides the O(n) worst case.
  • Inorder traversal does not prove strict validity when duplicate policy is unspecified.
  • Deleting a two-child node requires a consistent successor/predecessor replacement and relink.

Explain It in an Interview

State the duplicate rule and the interval owned by each recursive call. For search, name the subtree discarded by each comparison. Give complexity in terms of height first, then translate to balanced and worst-case bounds. Do not call every binary tree a BST.

Build and Query a Binary Search Tree(opens in a new tab) practices directed descent. Validate a Binary Search Tree(opens in a new tab) tests the global lower/upper-bound invariant.

Template To Memorize

Learn this shape by heart; most problems in this family change only one or two lines of it.

Binary search tree with limits

Every node lives inside its (low, high) bounds.

The tree is a binary search tree and you validate it, search it, or use its sorted order.

Trigger words

  • valid bst
  • binary search tree
  • k-th smallest in bst
  • lca in bst
  • inorder is sorted
def is_valid_bst(root):
    def check(node, low, high):
        if node is None:
            return True
        if node.val <= low or node.val >= high:
            return False
        left_ok = check(node.left, low, node.val)
        right_ok = check(node.right, node.val, high)
        return left_ok and right_ok

    return check(root, float('-inf'), float('inf'))

Spot it when

  • 'Valid BST'.
  • 'k-th smallest', 'lowest common ancestor in a BST'.

Remember

  • Every node must respect all of its ancestors, not only its parent.
  • An in-order traversal of a BST visits values in sorted order.

How problems bend it

  • k-th smallest: Do an in-order traversal and stop at the k-th visited node.
  • Lowest common ancestor: If both values are smaller go left, if both are bigger go right, otherwise this node is the answer.
  • Search or insert a value: Walk one path: go left when the value is smaller than node.val, right when bigger; a search stops at a match, an insert hangs a new node where the walk falls off the tree.

Python Version Note

Python 3.11+

The examples use standard Python containers and syntax available in the supported browser runtime; Binary Search Tree itself is taught as an interview abstraction.

Verify in Python docs(opens in a new tab)

Complexity & Invariants

Interview bounds depend on the stated representation, input model, and real Python operations.

OperationAverageWorstInterview note
Search or insert one valueO(h)O(n)h is actual tree height; these iterative operations do not rebalance. Stored tree uses O(n).
Build, traverse and answer q queriesO((n + q) * h + n)O(n * n + q * n)n insert attempts, q queries, h height. Includes tree, ordered output, query results and recursive inorder frames.
Validate inherited boundsO(n)O(n)At most n reachable numeric nodes; validation may stop early and recursion remains height-bounded.

Space

O(1) for search or insert one value; O(n + q + h) for build, traverse and answer q queries; O(h) for validate inherited bounds.

Assumptions

  • h is actual tree height; these iterative operations do not rebalance. Stored tree uses O(n).
  • n insert attempts, q queries, h height. Includes tree, ordered output, query results and recursive inorder frames.
  • At most n reachable numeric nodes; validation may stop early and recursion remains height-bounded.

Invariants Worth Saying Aloud

  1. Every left descendant is strictly below its inherited upper bound; every right descendant is strictly above its lower bound.
  2. The build Lab ignores duplicate values, while validation rejects duplicates in stored tree positions.
  3. Every search comparison keeps only the side that can contain the query.

When To Use Or Avoid Binary Search Tree

Use It When

  • Use bounds to validate an existing BST under an explicit duplicate policy.
  • Use directed descent when the tree structure is part of the problem.

Choose Another Tool When

  • Use a hash map for exact lookup when ordered tree structure is unnecessary.
  • Use bisect on compact static sorted input; list insertion still costs linear time.
  • Do not claim logarithmic operations without a height guarantee.

Common Pitfalls

These are the mistakes most likely to survive a happy-path example and fail a boundary case.

Checking only the immediate parent

A descendant can fit its parent while violating the root's inherited interval.

Prevent it: Validate the complete open interval carried from all ancestors.

Avoid

valid = value < parent

Use instead

valid = lower < value < upper

Allowing equality in a strict BST interval

Inclusive bounds admit a duplicate key that the validation contract rejects.

Prevent it: Use strict comparisons consistently under the no-duplicates policy.

Avoid

valid = lower <= value <= upper

Use instead

valid = lower < value < upper

Descending into the side excluded by comparison

A query smaller than the node cannot occur in its strictly larger right subtree.

Prevent it: Name the discarded side and keep only the possible side.

Avoid

next_node = node[2] if query < node[0] else node[1]

Use instead

next_node = node[1] if query < node[0] else node[2]

Reviewed References

Official Python documentation supports language behavior. Canonical problem pages provide additional practice context.