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.