-
Notifications
You must be signed in to change notification settings - Fork 0
/
kth-smallest-bst.py
executable file
·59 lines (41 loc) · 1007 Bytes
/
kth-smallest-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
49
50
51
52
53
54
55
56
57
58
59
class Node:
def __init__(self, data, left=None, right=None):
self.data = data
self.left = left
self.right = right
def create_bst(root, elements):
for item in elements:
node = Node(item)
root = insert_node(root, node)
return root
def insert_node(root, node):
current = root
current_parent = root
while current:
current_parent = current
if node.data < current.data:
current = current.left
else:
current = current.right
if root is None:
root = node
elif node.data < current_parent.data:
current_parent.left = node
else
current_parent.right = node
return root
def k_smallest_element_inorder(root, k):
stack = []
current = root
# Move of left extreme
while current:
stack.append(current)
current = current.left
# pop stack and process each node
current = stack.pop()
while current:
if __name__ == '__main__':
elements = [20, 8, 22, 4, 12, 10, 14 ]
root = None
root = create_bst(root, elements)
k_node = k_smallest_element_inorder(root, k)