← 返回 microsoft 的题目列表Kth Smallest Element in a Binary Search Tree (write full main, with follow-ups)
类型:online_judge
Problem: Kth Smallest Element in a Binary Search Tree (must provide runnable main and finish follow-ups)
Given the root of a Binary Search Tree (BST) and an integer k, return the k-th smallest value (1-indexed) among all node values in the BST.
Input (stdin)
Line 1: Level-order array representation of the tree (use null for missing nodes), e.g. [5,3,6,2,4,null,null,1]
Line 2: Integer k
Output (stdout)
A single integer: the k-th smallest value
Constraints
Number of nodes n: 1 <= n <= 2 * 10^5
1 <= k <= n
Node values fit in 32-bit signed integer
Follow-ups (must be addressed)
Do not store all node values in an auxiliary array; traverse on demand.
If there are many queries with different k, design for efficient repeated queries (e.g., subtree sizes or an iterator) and implement one approach.
If the tree supports dynamic insert/delete, explain how you would maintain support for k-th smallest queries and analyze complexity.
Example
Input
[3,1,4,null,2]
1
Output
1