CodingNodes / Trees / Kth Smallest Element In a Bst System design Space play · ←→ step · R restart

Problem

Given the root of a binary search tree and an integer k, return the k-th smallest value in the tree, counting from 1.

The tree is given in level order, with null for a missing child.

Constraints

  • 1 ≤ k ≤ number of nodes ≤ 10000
  • 0 ≤ Node.val ≤ 10000

Examples: pick one to animate

Solutions

TimeO(h + k) SpaceO(h)

Time: It walks down one path of height h to reach the smallest value, then pops k values, each node pushed and popped once.

Space: The stack holds one path from the root, at most h nodes. That is log n for a balanced tree and n for a chain.

Walking a search tree in order, left then node then right, visits the values from smallest to largest. Do that walk with an explicit stack: push nodes while going left, pop one, count it, then move to its right child. Count down k with each pop. When k reaches 0 the popped node is the answer, and the walk can stop early.