Kth Smallest Element in a BST

MediumBinary search treeLeetCode 230 ↗World 3-13
0:00 / 0:00

Find the kth smallest value in a BST. An inorder walk visits values in sorted order, so stop at the kth node you reach.

▼

The problem

LeetCode 230 (Medium). Given the root of a binary search tree and an integer k, return the k-th smallest value (1-indexed) of all the values in the tree.

The examples are LeetCode's: root = [3,1,4,null,2], k = 1 → 1 (scene 1) and root = [5,3,6,2,4,null,null,1], k = 3 → 3 (the rest of the video). Everything on screen is computed in code from those level-order arrays (buildTree and inorderEvents in src/slope.jsx): the tree layout, the in-order order, the preorder collection, the sorted list, the stack contents, the counts and the answers.

The simple way: collect every value with any traversal, sort them, and take index k − 1. That is O(n log n) time and O(n) space.

TRY IT ON LEETCODE ▶

The solution

def kthSmallest(root, k):
    stack, node, count = [], root, 0
    while True:
        while node:                 # slide left
            stack.append(node)
            node = node.left
        node = stack.pop()          # next smallest
        count += 1
        if count == k:
            return node.val
        node = node.right           # step right

Transcript

K-th Smallest Element in a BST. You're given the root of a binary search tree and a number k. Return the k-th smallest value stored anywhere in the tree.

Here's a tree: five at the root, three and six below it, two and four under three, and one under two. With k equal to three, we want the third smallest value. Listing the values in order, one, two, three: the answer is three.

The simple way ignores the shape. Visit every node, drop each value into a list, sort the list, and take the item at position k minus one. That works, but it stores all n values and sorts them all, even when k is one.

But a search tree is already sorted. Everything in a node's left subtree is smaller than it, and everything in its right subtree is bigger. So visit the left side first, then the node, then the right side. That's an in-order traversal, and it reads the values from smallest to largest. Count as you go, and stop at the k-th one.

In code, use a stack instead of recursion. Slide left as far as you can, pushing every node you pass. Then pop the top: that's the next smallest value. Count it, and if the count reaches k, return it. Otherwise, step to its right child, and repeat.

Let's run it with k equal to three. Slide down the left edge, pushing five, three, two and one. Pop one: count one. It has no right child, so pop again: two, count two. Two has no right child either, so pop three: count three. That's k, so the answer is three. Four, five and six are never counted.

The stack only holds one path from the root, so the space is O of the tree's height. The time is O of height plus k: one slide down, then k pops. In a balanced tree, that's log n plus k.

Go left, count, stop at k. That's K-th Smallest Element in a BST.