Kth Smallest in a BST

35 min · kthSmallest()

A search tree already keeps its values in order. The trick is choosing the walk that lets you cash in on that promise.

You're given the root of a valid binary search tree with distinct integer values and an integer k. Return the k-th smallest value, counting from 1.

For example, k = 1 asks for the smallest value and k = node count asks for the largest. You may trust that k always names a real node.

A few ground rules:

  • Every value in a node's left subtree is smaller than the node's value.
  • Every value in a node's right subtree is larger than the node's value.
  • The input tree is displayed as a level-order array, with null for a missing child.

Constraints

  • 1 <= k <= node count <= 10_000
  • All node values are distinct.
  • -2_147_483_648 <= node.val <= 2_147_483_647

Hints

Which traversal sorts a BST?

Visit the left subtree before the node, and the right subtree after it. Write down the order produced by that walk on a three-node BST.

Count visits, not values

During an in-order traversal, the first visited node is the smallest, the second is the second smallest, and so on. Increment a counter when you visit a node.

Don't finish work you don't need

Once the counter reaches k, return that value immediately. An explicit stack makes that early stop easy to control.

Follow-up

If the tree changed often and you had to answer thousands of k queries, what extra number could each node store to make every query faster?

Visible cases

Examples

Example 1

ready
Input
root = [
  3,
  1,
  4,
  null,
  2
]
k = 1
Expected
1
Why
the first in-order visit is 1

Example 2

ready
Input
root = [
  5,
  3,
  6,
  2,
  4,
  null,
  null,
  1
]
k = 3
Expected
3
Why
in-order starts 1, 2, 3

Example 3

ready
Input
root = [
  42
]
k = 1
Expected
42
Why
the only node is both smallest and largest

Interview signal

Asked at

AmazonGoogleUber
Loading editor

Console

ready to run

Ready to run.

3 cases are queued.

Run: visible + custom · Submit: full suite