codejump
MediumPro challengePythonJavaScriptTypeScript

BST — Kth Smallest Element

Data StructuresTreesBinary Search TreeDFS

solve(levelOrder, k) — given a binary search tree serialized level by level,
return the k-th smallest value (1-indexed). k is always valid.

The key property: an in-order traversal of a BST visits values in sorted
order. You do not need to collect everything — stop as soon as you reach the
k-th node.

Examples

solve([3, 1, 4, null, 2], 1)              → 1
solve([5, 3, 6, 2, 4, null, null, 1], 3)  → 3
solve([5, 3, 6, 2, 4, null, null, 1], 6)  → 6

Sample tests

Test #1Smallest value
Input: [[3,1,4,null,2],1]
Output: 1
Test #2Third smallest
Input: [[5,3,6,2,4,null,null,1],3]
Output: 3
Test #3Largest value
Input: [[5,3,6,2,4,null,null,1],6]
Output: 6