Kth Smallest Element in a BST

MediumTrees

Given the root of a binary search tree and a number k, return the k-th smallest value in the tree, counting from 1: k = 1 asks for the smallest.

On this page the tree is written in level order, top to bottom and left to right, with null where a child is missing: [6, 3, 8, 1] is 6 with children 3 and 8, and 3 with a left child 1.

Examples

Example 1
Input:  root = [9, 4, 13, 2, 6, null, 15], k = 3
Output: 6

In order the values are 2, 4, 6, 9, 13, 15, and the third is 6.

Example 2
Input:  root = [50, 30, 70, 20, 40], k = 1
Output: 20

The smallest value is the leftmost node, 20.

Constraints

  • The tree has n nodes, 1 ≤ k ≤ n ≤ 10⁴.
  • 0 ≤ node.val ≤ 10⁴, and no two nodes share a value.

Stuck?

Hint 1

An in-order walk (left subtree, node, right subtree) visits a search tree’s values from smallest to largest.

Hint 2

Walk in order, with a stack or with recursion, and count the nodes as you visit them. The node that brings the count to k is the answer, and you can stop there.

Still stuck? Read the solution

JavaScript
Loading the editor

Run checks your code against the 2 examples. Submit checks all 10 tests, most of them hidden.

Ctrl + Enter runs, and adding Shift submits. On a Mac, use ⌘.

blur