Member-only story

230. Kth Smallest Element in a BST

Machine Learning Quick Reads
2 min readOct 10, 2022

--

Medium

8506148Add to ListShare

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: root = [3,1,4,null,2], k = 1
Output: 1

Example 2:

Input: root = [5,3,6,2,4,null,null,1], k = 3
Output: 3

Constraints:

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

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?

Accepted

951,423

Submissions

1,374,916

Seen this question in a real interview before?

Yes

No

Companies

0 ~ 6 months6 months ~ 1 year1 year ~ 2 years

Uber|17

Amazon|9

Microsoft|4

Facebook|4

👏Wanna support me and become a medium member? Click here.

--

--

Machine Learning Quick Reads
Machine Learning Quick Reads

Written by Machine Learning Quick Reads

Lead Author: Yaokun Lin, Actuary | ML Practitioner | Apply Tomorrow's Technology to Solve Today's Problems

No responses yet