Skip to content

Kth Smallest Element in a BST

Find the k-th smallest value in a BST by walking it in order and stopping at the k-th node.

MediumTree DFS and BST
Solve on LeetCode

The problem

You get the root of a binary search tree and an integer k. Return the k-th smallest value in the tree, counting from 1. You can assume that k is between 1 and the number of nodes.

Input root = [20, 8, 30, 4, 12], k = 3

Output 12

In increasing order the values are 4, 8, 12, 20, 30, and the third one is 12.

Input root = [7, 3, 9, 1, 5, null, 11], k = 4

Output 7

The order is 1, 3, 5, 7, 9, 11, so the 4th smallest value is the root itself.

How to spot the pattern

  • The tree is a BST, so an in-order walk visits its values from smallest to largest.
  • You need a rank (the k-th value), and you can stop as soon as you reach it.

The idea

An in-order traversal (left subtree, then the node, then the right subtree) of a BST lists its values in sorted order. So the k-th node that this traversal visits holds the answer. Running the traversal with your own stack lets you stop right there, without touching the rest of the tree.

Brute force: Collect every value, sort them and take index k - 1, which costs O(n log n) time and O(n) space even when k is 1.

Step by step

  1. 1Start with an empty stack and node = root.
  2. 2Push nodes while moving left, until you fall off the tree.
  3. 3Pop a node: it holds the next smallest value, so count it.
  4. 4If it is the k-th node you have counted, return its value.
  5. 5Otherwise move to its right child and repeat from step 2.

See the pattern move

The tree dfs and bst pattern on a small example. Step through it, or press play.

Code

class Solution:
    def kthSmallest(self, root: Optional[TreeNode], k: int) -> int:
        stack = []
        node = root
        while True:
            while node:              # go as far left as possible
                stack.append(node)
                node = node.left
            node = stack.pop()       # the next smallest value
            k -= 1
            if k == 0:
                return node.val
            node = node.right

Complexity

Time

O(h + k)

Space

O(h)

You walk down at most h nodes before the first pop and then visit k nodes in order; the stack never holds more than one root-to-node path.

Watch out for

  • Visiting the right subtree before the left, which counts from the largest value instead of the smallest.
  • Counting from 0: with k = 1 you want the very first node the in-order walk pops.
  • Building the whole sorted list when you can stop at the k-th node.

Follow-up questions

What if the tree changes often and you need the k-th smallest many times?

Store the size of its subtree in every node and keep it updated on inserts and deletes. Then walk down in O(h): if the left subtree has at least k nodes go left, if it has exactly k - 1 the answer is the current node, otherwise go right with k reduced by the left size plus 1.

How would you find the k-th largest value?

Walk in reverse in-order (right subtree, node, left subtree) and stop at the k-th node.

In Hinglish

BST ka inorder traversal values ko sorted order mein deta hai. Stack ke saath inorder chalo aur k-th pop par ruk jao, poora tree ghoomne ki zaroorat nahi.

Related problems