Kth Smallest Element in a BST Visualizer & Step-by-Step Algorithm Solution

Find the kth smallest element (1-indexed) in a Binary Search Tree (BST) using in-order DFS traversal step counting.

Category: trees | Difficulty: Medium

Tags: BST, Binary Search Tree, DFS, Inorder Traversal, Recursion

Kth Smallest Element in a BST

3
1
2
4
100%
state
k1
count0
inorderVisited[]
resultnot found yet
Initialization
1/7
Explanation

Start kthSmallest with k = 1. In-order traversal visits BST nodes in strictly ascending order.

Source Code
1function kthSmallest(root, k) {
2 let count = 0, result = 0;
3 function inorder(node) {
4 if (!node) return;
5 inorder(node.left);
6 count++;
7 if (count === k) { result = node.val; return; }
8 inorder(node.right);
9 }
10 inorder(root);
11 return result;
12}