Kth Smallest Element in a BST

mediumTreesinorder traversal (iterative stack)B75Solve on LeetCode#230

Part of Practice: Construction & Hard Paths

Given the root of a binary search tree (BST) and an integer k, return the kth smallest value in the tree, counting from 1 — so k = 1 asks for the minimum.

The tree has n nodes with 1 ≤ k ≤ n ≤ 10,000. The values are the sorted order hiding in the tree's structure; you should not need to collect and sort them yourself.

Examples

Input:
root = [3,1,4,null,2], k = 1
Output:
1

The sorted values are [1,2,3,4]; the 1st smallest is 1.

Input:
root = [5,3,6,2,4,null,null,1], k = 3
Output:
3

Sorted values are [1,2,3,4,5,6]; the 3rd is 3.

Hints

One at a time — struggle first, peek second.

Your thinking space — verify on LeetCode, then mark it.