Kth Smallest Element in a BST - Problem

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.

A binary search tree (BST) is a tree where for every node, all values in the left subtree are smaller than the node's value, and all values in the right subtree are greater than the node's value.

Follow up: If the BST is modified frequently (insertions and deletions), how would you optimize the solution?

Input & Output

Example 1 — Basic BST
$ Input: root = [3,1,4,null,2], k = 1
Output: 1
💡 Note: The BST has values [1,2,3,4] in sorted order. The 1st smallest value is 1.
Example 2 — Find 3rd Smallest
$ Input: root = [5,3,6,2,4,null,null,1], k = 3
Output: 3
💡 Note: The sorted values are [1,2,3,4,5,6]. The 3rd smallest value is 3.
Example 3 — Single Node
$ Input: root = [1], k = 1
Output: 1
💡 Note: Only one node exists, so the 1st smallest is 1.

Constraints

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

Visualization

Tap to expand
Kth Smallest Element in a BST INPUT Binary Search Tree 3 1 4 2 left right root = [3,1,4,null,2] k = 1 Sorted order: 1, 2, 3, 4 Find 1st smallest 1 2 3 4 ALGORITHM STEPS 1 Start In-Order Visit left subtree first 2 Process Node Increment counter 3 Check Counter If count == k, return 4 Continue Right Visit right subtree Traversal Order: 1 1st 2 2nd 3 3rd 4 4th FINAL RESULT k=1: First visited node 3 1 FOUND! 4 2 Output: 1 1st smallest = 1 OK - Verified Key Insight: In-order traversal of a BST visits nodes in ascending sorted order. By counting nodes during traversal, we find the kth smallest when count equals k. Time: O(H + k), Space: O(H) where H is tree height. Early termination once kth element is found. TutorialsPoint - Kth Smallest Element in a BST | In-Order Traversal with Counter
Asked in
Google 15 Amazon 12 Microsoft 8 Facebook 6
255.0K Views
High Frequency
~15 min Avg. Time
8.5K Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen