Learn
Practice
Newsletter
Resources
Mobile
New
F
Toggle theme
0
F
0
Toggle menu
Animations
← Back to All Animations
Kth Smallest Element in a BST
Bookmark
Input
Example 1
Example 2
Example 3
Custom
tree
=
[3, 1, 4, null, 2]
,
k
=
1
3
1
4
2
k = 1
stack
sorted
inorder visits BST values in ascending order
3
1
4
2
k = 1
stack
sorted
inorder visits BST values in ascending order
3
curr
1
4
2
k = 1
stack
sorted
k =
1
, current = root =
3
3
curr
1
4
2
k = 1
stack
3
top
sorted
stack.push(
3
)
3
1
curr
4
2
k = 1
stack
3
top
sorted
current = current.left =
1
3
1
curr
4
2
k = 1
stack
3
1
top
sorted
stack.push(
1
)
3
1
4
2
k = 1
stack
3
1
top
sorted
no left child:
current = null
3
1
curr
4
2
k = 1
stack
3
top
sorted
current = stack.pop() =
1
3
1
#1
curr
4
2
k = 0
stack
3
top
sorted
1
1st
1
is the 1st smallest,
k -= 1 →
0
3
1
#1
curr
4
2
k = 0
stack
3
top
sorted
1
1st
k = 0:
1
is the 1st smallest
3
1
#1
4
2
k = 0
stack
3
sorted
1
1st
return 1
algo
master
.
io
Step:
Start: the 1st node visited in inorder is the 1st smallest
0 / 9
Input
Example 1
Example 2
Example 3
Custom
tree
=
[3, 1, 4, null, 2]
,
k
=
1
0 / 9
algo
master
.
io
Step:
Start: the 1st node visited in inorder is the 1st smallest