Problem · Tree
Kth Smallest Element in a Binary Search Tree
Learn this problemProblem statement
Insert the values in insertionOrder into an initially empty binary search tree in the given order. Then return the kth-smallest key, where k is one-indexed.
Use an iterative inorder traversal and stop as soon as the kth node is visited.
Function
kthSmallest(insertionOrder: int[], k: int) → intExamples
Example 1
insertionOrder = [5,3,6,2,4,1]k = 3return = 3The inorder sequence is [1,2,3,4,5,6], whose third value is 3.
Example 2
insertionOrder = [2,1,3]k = 1return = 1The first node visited by inorder traversal has key 1.
Constraints
1 <= insertionOrder.length <= 100000.- All values in
insertionOrderare distinct signed32-bit integers. 1 <= k <= insertionOrder.length.