KatInterview

230. Kth Smallest Element in a BST

MediumSolutions in Python, Java, C++, TypeScript

Read the full problem statement on LeetCode and try it first. Below is how to approach it in an interview, followed by a complete answer in each language.

Approach

The problem asks us to find the k-th smallest element in a Binary Search Tree (BST). The fundamental property of a BST is that an in-order traversal (Left subtree -> Root -> Right subtree) visits the nodes in ascending order of their values. This property is the key to solving the problem efficiently.

Solution

Kth Smallest Element in a BST in Python

# Definition for a binary tree node.
# class TreeNode:
#     def __init__(self, val=0, left=None, right=None):
#         self.val = val
#         self.left = left
#         self.right = right
class Solution:
    def kthSmallest(self, root: Optional[TreeNode], k: int) -> int:
        stack = []
        curr = root

        # The loop continues as long as there are nodes to process, either
        # from the current pointer or from the stack.
        while curr or stack:
            # Traverse as far left as possible, pushing nodes onto the stack.
            while curr:
                stack.append(curr)
                curr = curr.left
            
            # At this point, `curr` is None, and the top of the stack is the next
            # node in the in-order sequence.
            curr = stack.pop()

            # Decrement k. If it becomes 0, we've found the k-th smallest element.
            k -= 1
            if k == 0:
                return curr.val

            # Move to the right subtree to continue the in-order traversal.
            curr = curr.right
        
        # This part is unreachable given the problem constraints (1 <= k <= n).
        return -1

Kth Smallest Element in a BST in Java

/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode() {}
 *     TreeNode(int val) { this.val = val; }
 *     TreeNode(int val, TreeNode left, TreeNode right) {
 *         this.val = val;
 *         this.left = left;
 *         this.right = right;
 *     }
 * }
 */
import java.util.Stack;

class Solution {
    public int kthSmallest(TreeNode root, int k) {
        Stack<TreeNode> stack = new Stack<>();
        TreeNode curr = root;

        // The loop continues as long as there are nodes to process, either
        // from the current pointer or from the stack.
        while (curr != null || !stack.isEmpty()) {
            // Traverse as far left as possible, pushing nodes onto the stack.
            while (curr != null) {
                stack.push(curr);
                curr = curr.left;
            }

            // At this point, `curr` is null, and the top of the stack is the next
            // node in the in-order sequence.
            curr = stack.pop();

            // Decrement k. If it becomes 0, we've found the k-th smallest element.
            k--;
            if (k == 0) {
                return curr.val;
            }

            // Move to the right subtree to continue the in-order traversal.
            curr = curr.right;
        }

        // This part should not be reached given the problem constraints (1 <= k <= n).
        return -1; 
    }
}

Kth Smallest Element in a BST in C++

/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode() : val(0), left(nullptr), right(nullptr) {}
 *     TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
 *     TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
 * };
 */
#include <stack>

class Solution {
public:
    int kthSmallest(TreeNode* root, int k) {
        std::stack<TreeNode*> s;
        TreeNode* curr = root;

        // The loop continues as long as there are nodes to process, either
        // from the current pointer or from the stack.
        while (curr != nullptr || !s.empty()) {
            // Traverse as far left as possible, pushing nodes onto the stack.
            while (curr != nullptr) {
                s.push(curr);
                curr = curr->left;
            }

            // At this point, `curr` is null, and the top of the stack is the next
            // node in the in-order sequence.
            curr = s.top();
            s.pop();

            // Decrement k. If it becomes 0, we've found the k-th smallest element.
            k--;
            if (k == 0) {
                return curr->val;
            }

            // Move to the right subtree to continue the in-order traversal.
            curr = curr->right;
        }

        // This part should not be reached given the problem constraints (1 <= k <= n).
        return -1; 
    }
};

Kth Smallest Element in a BST in TypeScript

/**
 * Definition for a binary tree node.
 * class TreeNode {
 *     val: number
 *     left: TreeNode | null
 *     right: TreeNode | null
 *     constructor(val?: number, left?: TreeNode | null, right?: TreeNode | null) {
 *         this.val = (val===undefined ? 0 : val)
 *         this.left = (left===undefined ? null : left)
 *         this.right = (right===undefined ? null : right)
 *     }
 * }
 */

function kthSmallest(root: TreeNode | null, k: number): number {
    const stack: TreeNode[] = [];
    let curr: TreeNode | null = root;

    // The loop continues as long as there are nodes to process, either
    // from the current pointer or from the stack.
    while (curr !== null || stack.length > 0) {
        // Traverse as far left as possible, pushing nodes onto the stack.
        while (curr !== null) {
            stack.push(curr);
            curr = curr.left;
        }

        // At this point, `curr` is null, and the top of the stack is the next
        // node in the in-order sequence. Non-null assertion is safe because
        // the outer loop condition guarantees the stack is not empty here.
        curr = stack.pop()!;

        // Decrement k. If it becomes 0, we've found the k-th smallest element.
        k--;
        if (k === 0) {
            return curr.val;
        }

        // Move to the right subtree to continue the in-order traversal.
        curr = curr.right;
    }

    // This part should not be reached given the problem constraints (1 <= k <= n).
    // We return -1 as a fallback, although it's technically unreachable.
    return -1;
};

Preparing for interviews beyond LeetCode? Practise system design, SQL and behavioral questions with an in-browser runner on KatInterview.

LeetCode is a trademark of LeetCode LLC. KatInterview is not affiliated with LeetCode.