 All Problems
Kth Smallest Element in a BST
medium
tree
depth-first search
binary search tree
binary tree
amazon
google
facebook

Given the root of a binary search tree, and an integer k, return the kth smallest value (1-indexed) of all the values of the nodes in the tree.

Example 1:

Input:
3 1 4 null 2
1
Output: 1

Example 2:

Input:
5 3 6 2 4 null null 1
3
Output: 3

Constraints:

  • The number of nodes in the tree is n
  • 1 ≤ k ≤ n ≤ 10⁴
  • 0 ≤ Node.val ≤ 10⁴

Follow-up: If the BST is modified often (frequent inserts/deletes) and you need to frequently find the kth smallest, how would you optimize?

Input format: First line: BST in BFS level-order (null for missing). Second line: integer k.

Output format: The kth smallest value.

Run to check your code against the sample cases, or submit to run every case