Kth Smallest Element in a BST - Problem
Given the root of a binary search tree and an integer
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
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
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
โ Linear Growth
Space Complexity
O(H)
O(H) for recursion stack or iterative stack, where H is tree height
โ 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)
๐ก
Explanation
AI Ready
๐ก Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code