Kth Smallest Element in a BST

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

Follow up: If the BST is modified often (i.e., we can do insert and delete operations) and you need to find the kth smallest frequently, how would you optimize?

Example 1
        3
       / \
      1   4
       \
        2
Inputroot = [3,1,4,null,2], k = 1
Output1
The smallest value in the BST is 1.
Example 2
        5
       / \
      3   6
     / \
    2   4
   /
  1
Inputroot = [5,3,6,2,4,null,null,1], k = 3
Output3
The values in sorted order are [1, 2, 3, 4, 5, 6], so the 3rd smallest value is 3.

Constraints

  • The number of nodes in the tree is n.
  • 1 <= k <= n <= 10^4
  • 0 <= Node.val <= 10^4

Asked at 11 companies

</>

Your Solution

(Ctrl/Cmd + Enter)

Switching Language

Loading template...

Loading...

Sign in to save your progress

AI code evaluation

Get a correctness verdict, missed edge cases, and complexity analysis of your solution.

Sign in to evaluate