Algo-Sim › Binary Trees & BST

Kth Smallest Element in a BST

Medium · Binary Trees & BST · step through it in Java, Python and C++ on your own input

An iterative inorder walk reaches BST values in ascending order; stop at the kth one.

Problem

Given the root of a binary search tree and k, return the kth smallest value in the tree, counting from 1.

Constraints

Edge cases to test

Follow-up questions

What if the tree changes often and you query often?
Store each node’s subtree size, then pick left or right by size: O(h) per query and update.
What is the cost of the inorder walk?
O(h + k): it stops as soon as it reaches the k-th value.

Solution

Java

public int kthSmallest(TreeNode root, int k) {
    Deque<TreeNode> stack = new ArrayDeque<>();
    TreeNode curr = root;
    while (true) {
        while (curr != null) {
            stack.push(curr);
            curr = curr.left;
        }
        curr = stack.pop();
        if (--k == 0) return curr.val;
        curr = curr.right;
    }
}

Python

def kth_smallest(root, k):
    stack = []
    curr = root
    while True:
        while curr:
            stack.append(curr)
            curr = curr.left
        curr = stack.pop()
        k -= 1
        if k == 0:
            return curr.val
        curr = curr.right

C++

#include <bits/stdc++.h>
using namespace std;

class Solution {
  public:
    int kthSmallest(TreeNode *root, int k) {
        deque<TreeNode *> stack = {};
        TreeNode *curr = root;
        while (true) {
            while (curr != nullptr) {
                stack.push_back(curr);
                curr = curr->left;
            }
            curr = stack.back();
            stack.pop_back();
            if (--k == 0)
                return curr->val;
            curr = curr->right;
        }
    }
};

More Binary Trees & BST problems