Given the root of a binary search tree and an integer k, return the kth smallest value (1-indexed) of all the values of the nodes in the tree.
root = [3,1,4,null,2], k = 11root = [5,3,6,2,4,null,null,1], k = 33count[0]--. We have found one more in-order value.count[0] == 0 → found! result[0] = node.val; stop traversal.By counting as we go (decrementing from k to 0), we avoid building the full sorted list. We stop as soon as the k-th node is reached — making it O(H+k) instead of O(n).
A BST's core property: every node in the left subtree is smaller, and every node in the right subtree is larger. In-order traversal (left → node → right) leverages this to visit all nodes in non-decreasing order. The first node visited is the global minimum, the second is the second smallest, and so on. Counting down from k to 0 pinpoints the k-th element without materialising the full sorted sequence. Using int[] count (a mutable array wrapper) lets the counter be shared across recursive calls in Java.
You could copy every value into an array, sort it, and pick index k −1. But a search tree already gives sorted order through an inorder traversal. And we can stop as soon as we reach the k-th value.
Inorder visits left, then the node, then right. In a search tree, that means values come out from smallest to largest. Count each node as it is visited. When the count reaches k, that node is the answer, and you can stop.
Inorder of a search tree is sorted. Stop early as soon as you have counted k nodes.
Run the animation above on your own input, or watch the 1:49 video explanation of Kth Smallest Element in a BST with a dry run and Java code.