Skip to content

Commit dd0d0b4

Browse files
committed
Solve LC > kth-smallest-element-in-a-bst
1 parent 4b0908b commit dd0d0b4

File tree

1 file changed

+26
-0
lines changed

1 file changed

+26
-0
lines changed
Lines changed: 26 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,26 @@
1+
class TreeNode:
2+
def __init__(self, val=0, left=None, right=None):
3+
self.val = val
4+
self.left = left
5+
self.right = right
6+
7+
class Solution:
8+
"""
9+
Time Complexity: O(n)
10+
Space Complexity: O(k)
11+
"""
12+
13+
def inOrder(self, root: TreeNode, asc_sorted_list: list[int], k: int) -> None:
14+
if root.left:
15+
self.inOrder(root.left, asc_sorted_list, k)
16+
17+
asc_sorted_list.append(root.val)
18+
19+
if len(asc_sorted_list) < k and root.right:
20+
self.inOrder(root.right, asc_sorted_list, k)
21+
22+
def kthSmallest(self, root: TreeNode, k: int) -> int:
23+
asc_sorted_list = []
24+
self.inOrder(root, asc_sorted_list, k)
25+
26+
return asc_sorted_list[k - 1]

0 commit comments

Comments
 (0)