Back to course home
0% completed
Vote For New Content
Kth Smallest Element in a BST (medium)
Problem Statement
Given the root
of a binary search tree (BST) and an integer k
, return the k-th smallest value
in the tree.
The values in the BST are unique.
. Examples
Example 1:
- Input: root =
[5, 3, 8, 2, 4, 7, 9, 1]
, k =3
5
/ \
3 8
/ \ / \
2 4 7 9
/
1
- Expected Output:
3
- Justification: The sorted order of the elements is
[1, 2, 3, 4, 5, 7, 8, 9]
. The 3rd smallest value is3
.
Example 2:
- Input: root =
[6, 4, 8, 2, 5, 7, 9, 1, 3]
, k =5
6
/ \
4 8
/\ / \
2 5 7 9
/ \
1 3
- Expected Output:
5
- Justification: The sorted order of the elements is
[1, 2, 3, 4, 5, 6, 7, 8, 9]
. The 5th smallest value is5
.
Example 3:
- Input: root =
[10, 5, 15, 3, 7, 13, 18, 2, 4, 6, 8]
, k =6
10
/ \
5 15
/| / \
3 7 13 18
/| | |
2 4 6 8
- Expected Output:
7
- Justification: The sorted order of the elements is
[2, 3, 4, 5, 6, 7, 8, 10, 13, 15, 18]
. The 6th smallest value is7
.
Constraints:
- The number of nodes in the tree is n.
- 1 <= k <= n <= 10<sup>4</sup>
- 0 <= Node.val <= 10<sup>4</sup>
Try it yourself
Try solving this question here:
Python3
Python3
. . . .
.....
.....
.....
Like the course? Get enrolled and start learning!
Table of Contents
Contents are not accessible
Contents are not accessible
Contents are not accessible
Contents are not accessible
Contents are not accessible