-
Notifications
You must be signed in to change notification settings - Fork 1
/
binarySearchTree.py
69 lines (59 loc) · 1.56 KB
/
binarySearchTree.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
60
61
62
63
64
65
66
67
68
69
'''
Author: Davide Pollicino
Date: 05/02/2020
Summary: Console application that stores different numbers in a BST (Binary Search Tree) and print the BST in according
with the inorder, preorder and postOrder algorithms.
'''
class Node:
def __init__(self, key):
self.left = None
self.right = None
self.val = key
# A utility function to insert a new node with the given key
def insert(root,node):
if root is None:
root = node
else:
if root.val < node.val:
if root.right is None:
root.right = node
else:
insert(root.right, node)
else:
if root.left is None:
root.left = node
else:
insert(root.left, node)
# Travers our BST using the inorder algorithm
def inorder(root):
if root:
inorder(root.left)
print(root.val)
inorder(root.right)
# Travers our BST using the preOrder algorithm
def preoder(root):
if root:
print(root.val)
preoder(root.left)
preoder(root.right)
# Travers our BST using the postOrder algorithm
def postorder(root):
if root:
postorder(root.left)
postorder(root.right)
print(root.val)
# drive code for testing purposes
r = Node(50)
insert(r,Node(15))
insert(r,Node(34))
insert(r,Node(56))
insert(r,Node(32))
insert(r,Node(11))
insert(r,Node(99))
# Print inoder traversal of the BST
print('Inorder: ')
inorder(r)
print('Postorder: ')
postorder(r)
print('Preorder: ')
preoder(r)