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

Lesson 10.10 of 14 in this module Unrolled Pro

Kth Smallest Element in a BST

The k-th smallest value in a binary search tree. From listing every value in order and indexing (O(n) time and memory), to an iterative in-order walk that stops after k values (O(h + k)), to storing each node's subtree size so a single root-to-leaf walk finds any rank in O(h). Then frequent queries with inserts (an order-statistic tree), the reverse question of a value's rank, ranks on a live leaderboard of model scores, and when a sorted list with bisect is simpler.

about 10 min 4 Python examples 2 quick checks

Problem. Given the root of a binary search tree and an integer k (1-based), return the k-th smallest value.

text
      5
     / \
    3   6           k = 4   →   4       (sorted: 1, 2, 3, 4, 5, 6)
   / \
  2   4
 /
1

Lesson 10.9 showed that an in-order walk of a BST visits values in sorted order. The questions here are how early you can stop, and how to answer many such queries on a tree that keeps changing.

ML context. "What is the k-th best score?" and its reverse "what rank is this score?" are leaderboard and percentile questions: the rank of a new checkpoint among all evaluated ones, the percentile of a request's latency among recent requests, the median of a growing set of scores. When the set changes constantly, recomputing from scratch is wasteful; a tree that stores subtree counts answers both in O(log n) (Changes A and B).


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 "Kth Smallest Element in a BST"

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