forked from kamyu104/LeetCode-Solutions
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathkth-smallest-element-in-a-bst.py
48 lines (37 loc) · 1.01 KB
/
kth-smallest-element-in-a-bst.py
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
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
# Time: O(max(h, k))
# Space: O(h)
class Solution(object):
# @param {TreeNode} root
# @param {integer} k
# @return {integer}
def kthSmallest(self, root, k):
s, cur, rank = [], root, 0
while s or cur:
if cur:
s.append(cur)
cur = cur.left
else:
cur = s.pop()
rank += 1
if rank == k:
return cur.val
cur = cur.right
return float("-inf")
# time: O(max(h, k))
# space: O(h)
from itertools import islice
class Solution2(object):
def kthSmallest(self, root, k):
"""
:type root: TreeNode
:type k: int
:rtype: int
"""
def gen_inorder(root):
if root:
for n in gen_inorder(root.left):
yield n
yield root.val
for n in gen_inorder(root.right):
yield n
return next(islice(gen_inorder(root), k-1, k))