Kth Smallest Element in a BST
Problem Statement
You are given the root of a binary search tree and an integer k.
Return the k-th smallest value among all node values in the tree. k counts from 1: k = 1 is the smallest value.
The root of a binary search tree with n nodes, and an integer k.
The k-th smallest value in the tree.
The values in order are 1, 2, 3, 4. The 1st is 1.
The values in order are 1, 2, 3, 4, 5, 6. The 3rd is 3.
- β’ The number of nodes is n
- β’ 1 β€ k β€ n β€ 10^4
- β’ 0 β€ Node.val β€ 10^4
- β’ Follow-up: if the tree changes often (inserts and deletes) and k-th queries are frequent, how would you make each query fast?
Pattern Recognition Clues
Recognising these key signals in the problem description immediately identifies the pattern:
Approach Complexity Ladder
Inorder walk into an array, then read position k β 1
Walk in order with a stack and return the value at the k-th pop
An inorder walk gives the values in sorted order. Store all n values in an array, then return the one at index k β 1. The walk visits every node, even though only one value is needed.
Recognition rule for this sub-pattern:
Unlock Complete Visual Walkthrough & Optimal C++
The interactive animated dry-run player, optimized C++ implementation, state invariant derivations, and edge-case breakdown for this question are part of Brute2Best Pro. The anchor question of every sub-pattern is completely free.
First anchor question per pattern, Part 1 LLD & Module 1 C++ basics are 100% Free forever.
How this concept connects to System Design & C++ Systems
Top engineering interviews test whether you understand how algorithms like Tree DFS translate into production architectures and low-level memory mechanics.
Foundations: Object-Oriented Principles in C++23
Class invariants, pure virtual interfaces, and RAII smart pointers.
Food Delivery System (Zomato Architecture)
Real-world machine coding application of algorithms and design patterns.
Pointers vs References Deep Dive
Pointer arithmetic and memory layout under the hood.
Virtual Method Table (vtable) & Memory Layout
Polymorphism, vptr overhead, and multiple inheritance in memory.