forked from prabhupant/python-ds
-
Notifications
You must be signed in to change notification settings - Fork 0
/
kth_smallest_in_bst.py
49 lines (37 loc) · 921 Bytes
/
kth_smallest_in_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
"""
Print the kth smallest number in BST
The inorder traversal of BST gives elements in ascending order. So do inorder,
keep count and return the kth value
"""
class Node():
def __init__(self, val):
self.val = val
self.left = None
self.right = None
def inorder(root, k):
if not root:
return None
stack = []
counter = 1
while True:
if root:
stack.append(root)
root = root.left
else:
if not stack:
break
root = stack.pop()
if counter == k:
return root.val
else:
counter += 1
root = root.right
return "tree not big enough"
root = Node(5)
root.left = Node(3)
root.right = Node(7)
root.left.left = Node(2)
root.right.right = Node(4)
root.right.left = Node(6)
root.right.right = Node(8)
print(inorder(root, 3))