Practice · Trees · 9 of 12

Kth Smallest Value in a Binary Search Tree

You are given root, the root of a binary search tree, and a number k. The values in the tree are all different; every node's left subtree holds smaller values and its right subtree larger ones.

Return the kth smallest value in the tree, counting from 1, so k = 1 asks for the minimum.

Trees are written in level order, row by row from the top, with null where a node is missing: [4, 2, 7, null, 3] is 4 at the root, 2 and 7 below it, and 3 as the right child of 2.

Example 1

Input
root = [6, 3, 9, 1, 4, 8], k = 3
Output
4
In increasing order the values are 1, 3, 4, 6, 8, 9; the third is 4.

Example 2

Input
root = [2, null, 5], k = 1
Output
2
With no left child, the root itself is the smallest value.

Constraints

  • The tree holds n nodes, and 1 ≤ k ≤ n ≤ 1000.
  • Values are distinct, between 0 and 10⁴.