forked from DaleStudy/leetcode-study
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathppxyn1.py
More file actions
30 lines (24 loc) · 697 Bytes
/
Copy pathppxyn1.py
File metadata and controls
30 lines (24 loc) · 697 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, val=0, left=None, right=None):
# self.val = val
# self.left = left
# self.right = right
#idea : DFS (inorder)
#Time Complexity: O(n)
class Solution:
def kthSmallest(self, root: Optional[TreeNode], k: int) -> int:
stack = []
cnt = 0
curr = root
if not curr:
return
while curr or stack:
while curr:
stack.append(curr)
curr = curr.left
curr = stack.pop()
cnt += 1
if cnt == k:
return curr.val
curr = curr.right