51. Kth Smallest Element in a BST

Medium · Binary Tree

Given a binary search tree (BST) and an integer k, find the kth smallest element in the tree (1-indexed). The BST is provided as a level-order array where null represents a missing node. For example, [3,1,4,null,2] represents a tree with root 3, left child 1, right child 4, and 1's right child is 2. Return the value of the kth smallest node; for k=1, return the minimum value in the BST.

Examples

Example 1
Input: [[3,1,4,null,2], 1]
Output: 1
Explanation: In-order traversal: 1,2,3,4 → 1st smallest is 1
Example 2
Input: [[5,3,6,2,4,null,null,1], 3]
Output: 3
Explanation: In-order: 1,2,3,4,5,6 → 3rd smallest is 3

Constraints