Skip to content
mlmentorship

Kth Smallest Element in a BST

Use inorder as a sorted stream, count pops rather than descent, and add subtree counts only when repeated rank queries justify them.

Published · 22 min read ·Core ·Mixed

ML breadth · active recall

Practice before you read

8 minutes. Explain the mechanism, why it works, when it fails, and one alternative.

ML breadth · closed-book attempt

Kth Smallest Element in a BST

Explain the mechanism, why it works, when it fails, and one alternative.

Problem

Input. The root of a finite strict binary search tree and a one-based integer rank k. Output. Return the kth smallest stored value, not the node object or its depth. Rules. Every left descendant is smaller than its ancestor; every right descendant is larger. Values are distinct, and there are no cycles or shared children. Require 1 <= k <= the node count. Leave all nodes and links unchanged. Example. A tree with root 3, left child 1, right child 4, and 1.right = 2 has values [1, 2, 3, 4]. For k = 2, return 2.

08:00recommended time

Closing or reloading clears the scratchpad. Only score, weak rubric dimensions, attempt count, and retry date can be stored locally.

30-second answer map

Iterative inorder exposes BST values in ascending order, so the fourth pop is the answer.

Problem trace

Count a node when inorder visits it, not when it enters the stack

Input and goalReturn the `k`th smallest tree value.
Initialize traversalSet root=5, stack=[], and remaining k=4.
root=5pending stack []53724681
Original coordinate inventory
5root=5/\37/\/\2468|1
inputtree=[5,3,7,2,4,6,8,1], k=4cursorroot=5stack[]remaining4
root
(0, 3)
input
tree=[5,3,7,2,4,6,8,1], k=4
cursor
root=5

Recognize it
The input is a BST and the question asks for an order statistic, so inorder traversal produces the required sorted rank without sorting all values.
Keep true
Before each pop, the stack top is the smallest unvisited node reachable from the processed search frontier; completed pops are in strictly ascending BST order.
Reuse it
Use inorder as a sorted stream for BST rank, range, predecessor, and successor tasks, and stop as soon as the requested portion of that stream is consumed.
Set root=5, stack=[], and remaining k=4. Step through the frames to watch the state change. The last frame shows the answer or the stopping condition.
Check: Why does pushing node 5 not decrement k, while popping node 1 does?
Full interview answer 22 min read

Return the value at a requested ascending rank in a binary search tree.

Problem

Input. The root of a finite strict binary search tree and a one-based integer rank k.

Output. Return the kth smallest stored value, not the node object or its depth.

Rules. Every left descendant is smaller than its ancestor; every right descendant is larger. Values are distinct, and there are no cycles or shared children. Require 1 <= k <= the node count. Leave all nodes and links unchanged.

Example. A tree with root 3, left child 1, right child 4, and 1.right = 2 has values [1, 2, 3, 4]. For k = 2, return 2.

Picture

For rank four, push 5,3,2,1 down the left spine. Four pushes do not mean four values have been emitted.

ActionDeferred ancestors after actionRank still needed
Push through 15,3,2,1, top 14
Pop 15,3,23
Pop 25,32
Pop 3; enter its right child51
Push and pop 450: return 4

Problem trace

Separate three-node tree: rank belongs to emissions, not pushes

Worked example: count a node when inorder visits it, not when it enters the stackA root 2 can enter the stack before its left child 1. The visit order is still 1 then 2 then 3.Pushing discovers a node; inordervisiting emits its rankStack push order: two, then its leftchild one21213Actual inorder emissions: one, two,three123Rank 1 is visited value 1, not thefirst pushed value 2.
Read it this way: A root 2 can enter the stack before its left child 1. The visit order is still 1 then 2 then 3. For rank one, is the root pushed first automatically the first value visited?
Reference drawing

Problem trace

Count a node when inorder visits it, not when it enters the stack

Worked example: count a node when inorder visits it, not when it enters the stackA root 2 can enter the stack before its left child 1. The visit order is still 1 then 2 then 3.Pushing discovers a node; inordervisiting emits its rankStack push order: two, then its leftchild one21213Actual inorder emissions: one, two,three123Rank 1 is visited value 1, not thefirst pushed value 2.
Execution trace
Input and goalReturn the `k`th smallest tree value.
Initialize traversalSet root=5, stack=[], and remaining k=4.
root=5pending stack []53724681
Original coordinate inventory
5root=5/\37/\/\2468|1
inputtree=[5,3,7,2,4,6,8,1], k=4cursorroot=5stack[]remaining4
root
(0, 3)
input
tree=[5,3,7,2,4,6,8,1], k=4
cursor
root=5

Recognize it
The input is a BST and the question asks for an order statistic, so inorder traversal produces the required sorted rank without sorting all values.
Keep true
Before each pop, the stack top is the smallest unvisited node reachable from the processed search frontier; completed pops are in strictly ascending BST order.
Reuse it
Use inorder as a sorted stream for BST rank, range, predecessor, and successor tasks, and stop as soon as the requested portion of that stream is consumed.
Set root=5, stack=[], and remaining k=4. Step through the frames to watch the state change. The last frame shows the answer or the stopping condition.
Check: Why does pushing node 5 not decrement k, while popping node 1 does?
Read it this way: A root 2 can enter the stack before its left child 1. The visit order is still 1 then 2 then 3. For rank one, is the root pushed first automatically the first value visited?

Code

Use this node type for a local run.

from dataclasses import dataclass


@dataclass
class TreeNode:
   val: int
   left: "TreeNode | None" = None
   right: "TreeNode | None" = None
def kth_smallest(root: TreeNode | None, k: int) -> int:
   stack: list[TreeNode] = []

   while root or stack:
      while root:
         stack.append(root)
         root = root.left
      root = stack.pop()
      k -= 1
      if k == 0:
         return root.val
      root = root.right
   raise ValueError("k is larger than the tree")

Count Only Emitted Nodes

All left-subtree values precede a node; all right-subtree values follow it. That BST contract makes inorder a sorted stream.

After pushing a complete left spine, the stack top is the smallest unvisited node.

Pop it, decrement k, then either return or continue from its right child. The stack retains ancestors still awaiting emission.

In the example, returning four leaves root five and its entire right subtree unvisited.

For valid rank k, time is and space for height .

Even rank one may require a full-height descent. A BST is not necessarily balanced, so logarithmic height is not guaranteed.

The source expects a positive rank. Nonpositive or oversized ranks exhaust traversal and raise its same size error; an empty tree does too.

The platform supplies TreeNode with val, left, and right; this snippet assumes that definition.

Recall: Why not decrement on push? The fourth pushed node is one, but the fourth emitted value is four.

Rank from the Largest End

Choose this when: Rank orientation changes, but the strict BST contract stays the same.

Visit right, node, left. Decrement only on pop, as before.

def kth_largest_bst(root, rank):
   if rank <= 0:
      raise ValueError("positive rank required")
   stack = []
   while root or stack:
      while root:
         stack.append(root)
         root = root.right
      root = stack.pop()
      rank -= 1
      if rank == 0:
         return root.val
      root = root.left
   raise ValueError("rank exceeds size")

The second largest value in the pictured tree is seven. Reversing a comparison alone cannot reverse traversal order.

Time remains for valid ranks; stack space remains . No tree links change.

Precompute Counts for Repeated Queries

Choose this when: Many rank requests share an unchanged tree.

Count each subtree once. Its left size tells whether to descend left, emit the current node, or skip that whole prefix.

def bst_rank_queries(root, ranks):
   sizes = {}

   def measure(node):
      if node is None:
         return 0
      size = 1 + measure(node.left) + measure(node.right)
      sizes[id(node)] = size
      return size

   total = measure(root)
   result = []
   for rank in ranks:
      if not 1 <= rank <= total:
         result.append(None)
         continue
      node = root
      while node is not None:
         left_size = sizes.get(id(node.left), 0)
         if rank == left_size + 1:
            result.append(node.val)
            break
         if rank <= left_size:
            node = node.left
         else:
            rank -= left_size + 1
            node = node.right
   return result

Keys use object identity, not value or structural equality. Nodes need not be hashable.

Ranks 1,4,8,0 return [1,4,8,None]; invalid integer ranks return None rather than raising.

Preprocessing takes time and count storage; each query takes time. The returned list also stores one result per query.

This preprocessing is recursive, so deep trees can exceed Python’s recursion limit. Rebuild counts after mutations; balancing is a separate requirement.