Skip to content

Commit 716e712

Browse files
sangheestylekamyu104
authored andcommitted
add a solution (#30)
1 parent 4655b73 commit 716e712

File tree

1 file changed

+25
-0
lines changed

1 file changed

+25
-0
lines changed

Python/kth-smallest-element-in-a-bst.py

Lines changed: 25 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -21,3 +21,28 @@ def kthSmallest(self, root, k):
2121

2222
return float("-inf")
2323

24+
25+
# time: O(max(h, k))
26+
# space: O(h)
27+
28+
from itertools import islice
29+
30+
31+
class Solution2(object):
32+
def kthSmallest(self, root, k):
33+
"""
34+
:type root: TreeNode
35+
:type k: int
36+
:rtype: int
37+
"""
38+
def gen_inorder(root):
39+
if root:
40+
for n in gen_inorder(root.left):
41+
yield n
42+
43+
yield root.val
44+
45+
for n in gen_inorder(root.right):
46+
yield n
47+
48+
return next(islice(gen_inorder(root), k-1, k))

0 commit comments

Comments
 (0)