
Problem
Solution
Submissions
Kth Smallest Element in a BST
Certification: Intermediate Level
Accuracy: 0%
Submissions: 0
Points: 12
Write a C# program to implement the KthSmallest function, which finds the kth smallest element in a Binary Search Tree (BST). The function should take the root of a BST and an integer k, and return the kth smallest element in the tree.
Example 1
- Input: root = [3,1,4,null,2], k = 1
- Output: 1
- Explanation:
- Tree structure:
3
/ \
1 4
\
2 - The smallest element in this BST is 1.
- Tree structure:
Example 2
- Input: root = [5,3,6,2,4,null,null,1], k = 3
- Output: 3
- Explanation:
- Tree structure:
5
/ \
36
/ \
2 4
/
1 - The elements in ascending order are [1,2,3,4,5,6] and the 3rd element is 3.
- Tree structure:
Constraints
- The number of nodes in the tree is n, where 1 ≤ n ≤ 10^4
- 0 ≤ Node.val ≤ 10^4
- 1 ≤ k ≤ n
- Time Complexity: O(h + k) where h is the height of the tree
- Space Complexity: O(h) for recursion stack
Editorial
My Submissions
All Solutions
| Lang | Status | Date | Code |
|---|---|---|---|
| You do not have any submissions for this problem. | |||
| User | Lang | Status | Date | Code |
|---|---|---|---|---|
| No submissions found. | ||||
Solution Hints
- Use an in-order traversal to visit nodes in ascending order
- Keep a counter to track the position of the current node
- When the counter equals k, you've found the kth smallest element
- Try both recursive and iterative solutions
- Optimize by stopping the traversal once the kth element is found