Skip to content

Commit e6fdd80

Browse files
committed
solve : solve kth smallest element in a bst
1 parent f0f8b4d commit e6fdd80

File tree

1 file changed

+21
-0
lines changed

1 file changed

+21
-0
lines changed
Lines changed: 21 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,21 @@
1+
# TC : O(n)
2+
# SC : O(n)
3+
class Solution:
4+
def kthSmallest(self, root: Optional[TreeNode], k: int) -> int:
5+
n = 0
6+
stack = []
7+
cur = root
8+
9+
while cur or stack:
10+
while cur:
11+
stack.append(cur)
12+
cur = cur.left
13+
14+
cur = stack.pop()
15+
n += 1
16+
if n == k:
17+
return cur.val
18+
19+
cur = cur.right
20+
21+
return -1

0 commit comments

Comments
 (0)