Kth Smallest Element in a BST - Problem
Given the root of a binary search tree and an integer k, your task is to find and return the kth smallest value among all node values in the tree (using 1-based indexing).

A Binary Search Tree (BST) is a special tree where for every node, all values in the left subtree are smaller, and all values in the right subtree are larger than the node's value. This property gives us powerful traversal techniques!

Goal: Efficiently locate the kth smallest element without necessarily examining all nodes.
Input: Root of a BST and integer k
Output: The kth smallest value in the tree

Input & Output

example_1.py โ€” Basic BST
$ Input: root = [3,1,4,null,2], k = 1
โ€บ Output: 1
๐Ÿ’ก Note: The inorder traversal of the BST gives us [1,2,3,4]. The 1st smallest element is 1.
example_2.py โ€” Larger BST
$ Input: root = [5,3,6,2,4,null,null,1], k = 3
โ€บ Output: 3
๐Ÿ’ก Note: The inorder traversal yields [1,2,3,4,5,6]. The 3rd smallest element is 3.
example_3.py โ€” Single Node
$ Input: root = [1], k = 1
โ€บ Output: 1
๐Ÿ’ก Note: Tree has only one node, so the 1st (and only) smallest element is 1.

Visualization

Tap to expand
BST Inorder Traversal - Finding kth Smallest5371468Inorder Traversal Sequence:1(1st)3(2nd)4(3rd) โ† Stop here for k=3!5(4th)6(5th)... (no need to visit)๐ŸŽฏ Key Insight: Inorder traversal of BST gives sorted sequenceTime: O(H + k) | Space: O(H) where H = tree height
Understanding the Visualization
1
Start at Root
Begin traversal from the root of the BST
2
Go Left First
Always visit left subtree first (smaller values)
3
Process Current
Visit current node and increment counter
4
Go Right Next
Then visit right subtree (larger values)
5
Stop at k
Return value when counter reaches k
Key Takeaway
๐ŸŽฏ Key Insight: BST inorder traversal naturally produces sorted order, allowing us to stop at exactly the kth element without examining the entire tree!

Time & Space Complexity

Time Complexity
โฑ๏ธ
O(H + k)

Where H is tree height. We go down H levels, then visit at most k nodes in inorder

n
2n
โœ“ Linear Growth
Space Complexity
O(H)

O(H) for recursion stack or iterative stack, where H is tree height

n
2n
โœ“ Linear Space

Constraints

  • The number of nodes in the tree is n
  • 1 โ‰ค k โ‰ค n โ‰ค 104
  • 0 โ‰ค Node.val โ‰ค 104
  • The tree is guaranteed to be a valid BST
  • k is guaranteed to be valid (1 โ‰ค k โ‰ค number of nodes)
Asked in
Google 45 Amazon 38 Microsoft 32 Meta 28
78.0K Views
High Frequency
~15 min Avg. Time
2.8K 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