-
Notifications
You must be signed in to change notification settings - Fork 0
/
230_kthSmallestElementinBST.py
40 lines (33 loc) · 1.13 KB
/
230_kthSmallestElementinBST.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
# Definition for a binary tree node.
class TreeNode(object):
def __init__(self, val=0, left=None, right=None):
self.val = val
self.left = left
self.right = right
class Solution(object):
def kthSmallest(self, root, k):
"""
:type root: TreeNode
:type k: int
:rtype: int
"""
# Use Inorder traversal to generate a list of elements in ascending order - could be done both in recursive and iterative way
# Can optimize iteratvie way to O(H+K) from O(n) time complexity and O(H) space complexity
stack = []
while True:
while root:
stack.append(root)
root = root.left
root = stack.pop()
# # instead of appending to the result in the inorder traversal - K statement
k -= 1
if not k:
return root.val
root = root.right
if __name__ == '__main__':
root = TreeNode(3)
root.left = TreeNode(1)
root.left.right = TreeNode(2)
root.right = TreeNode(4)
k = 1
print(Solution().kthSmallest(root, 1))