VFlash: Fast, Accurate Visual Planning via Flash Primitive Decoding
u_Unrolled
DSA for AI/ML · Module 10: Trees and BSTs

Lesson 10.9 of 14 in this module Unrolled Pro

Validate Binary Search Tree

Check that every node is greater than everything in its left subtree and smaller than everything in its right subtree. From the tempting check against direct children only (wrong), to comparing each node with its whole subtrees (O(n²)), to an in-order traversal that must be strictly increasing, and to passing a (low, high) range down the tree, both O(n) with early exit. Then search and insert in a BST, duplicate keys, recovering a tree whose two nodes were swapped, and deep trees.

about 10 min 4 Python examples 2 quick checks

Problem. Return whether a binary tree is a valid binary search tree (BST): for every node, all values in its left subtree are strictly less than its value, and all values in its right subtree are strictly greater.

text
   2              5
  / \            / \
 1   3   True   1   6       False   (3 is in 5's right subtree but 3 < 5)
                   / \
                  3   7

The ordering is what makes a BST useful: search, insert and delete follow one root-to-leaf path, O(h) (O(log n) when balanced, lesson 10.6), and an in-order walk lists the values sorted. The trap is that the rule is about whole subtrees, not just children.

ML context. Ordered tree indexes sit under databases, feature stores and the sorted containers in Python libraries; an index whose ordering is violated silently returns wrong lookups, which is exactly what a validator catches. The bound passing in Optimisation B is also how a decision tree routes a sample: each split narrows the feature range a leaf covers (lesson 10.14).


1. Step 1: Clarify

That's the preview. Modules 00–01 are free; this lesson is part of Unrolled Pro.
Staff AI & Pro Tier Lesson

Unlock "Validate Binary Search Tree"

The foundations are free forever. Unrolled Pro unlocks the complete lesson, production architectures, and 55 battle-tested ML system design case studies.

Everything included with Pro:
All 234+ Deep-Dive Lessons across transformer internals, inference, RAG & agents
55 Staff-Level ML & System Design Case Studies with mathematical capacity estimates
AI Engineer Sheet & Exercises with worked solutions, self-checks, and code
100 Landmark Research Papers guided walkthroughs & progress tracking
14-Day Money-Back Guarantee — 100% full refund if you aren't satisfied
View Plans & Unlock All Lessons

From ₹167/mo (~$2/mo) · Cancel anytime · Instant activation

100% Risk-Free: 14-day no-questions-asked money-back guarantee