Loading content...
You are given the root node of a Binary Search Tree (BST) and a positive integer k. Your task is to find and return the value of the node that holds the k-th smallest element in the tree when all node values are considered in ascending order.
Recall that a Binary Search Tree is a binary tree where for every node, all values in its left subtree are strictly smaller than the node's value, and all values in its right subtree are strictly larger. This property makes BSTs particularly efficient for ordered operations.
The ranking is 1-indexed, meaning k = 1 refers to the smallest element, k = 2 refers to the second smallest, and so on. You are guaranteed that the value of k will always be valid (i.e., 1 ≤ k ≤ total number of nodes).
root = [3,1,4,null,2]
k = 11The BST contains values [1, 2, 3, 4] when traversed in-order. The 1st smallest element is 1.
root = [5,3,6,2,4,null,null,1]
k = 33The BST contains values [1, 2, 3, 4, 5, 6] in sorted order. The 3rd smallest element is 3.
root = [4,2,6,1,3,5,7]
k = 44This is a perfectly balanced BST with values [1, 2, 3, 4, 5, 6, 7]. The 4th smallest element (the median) is 4.
Constraints