Visualize kth smallest in a BST step by step. Watch inorder traversal visit nodes in sorted order and stop the moment the count reaches k.
About this algorithm
To find the k-th smallest value in a binary search tree, read the tree in order (left subtree, node, right subtree), which visits the values from smallest to largest, and count as you go. The k-th node you visit is the answer, and the walk can stop right there. This is LeetCode 230.
Use this when the data is already in a search tree and you need a rank question answered: the 3rd cheapest price, the median of a small set, the k-th earliest booking. Copying the tree into a sorted list first would also work, but it always costs O(N), while counting in order stops after k visits. For a plain unsorted array, use quickselect or a heap of size k instead. If the same tree gets many rank questions while it keeps changing, store the size of each node's left subtree, as an order-statistic tree does; then each question takes O(H) instead of O(H + k).
From the root, keep moving to the left child, remembering each node you pass. The leftmost node holds the smallest value.
When a node has no unvisited left side, visit it: add one to the count. If the count equals k, this value is the answer and you stop.
After visiting a node, run the same process on its right child. When that subtree is finished, return to the nearest remembered node above, which is the next one to visit.
If the whole tree is read and the count never reached k, the tree has fewer than k nodes.
The page loads 20 at the root, 10 and 30 below it, 5 and 15 under 10 and 25 and 35 under 30, with k set to 3 (the slider goes from 1 to 7). The walk goes left from 20, left from 10 and left from 5, which has no left child. Visit 5: count 1. 5 has no right child, so return to 10. Visit 10: count 2. Go right to 15 and check its empty left side. Visit 15: count 3, which equals k, so the 3rd smallest is 15. The walk stops with 20, 30, 25 and 35 never counted. The full in-order list would be 5, 10, 15, 20, 25, 30, 35, so k = 7 gives 35 after a walk through the whole tree.
A recursive in-order needs a way to stop once the answer is found, such as a shared flag or counter checked at the top of each call. The version with an explicit stack stops more naturally: pop, count, and return as soon as the count reaches k.
Time: the walk first goes down the left edge, H nodes, then visits k nodes in order, so it costs O(H + k), which is O(N) when k is close to N or the tree is a chain. Space: the recursion or stack holds the nodes waiting on the current path, at most the height H.