-
Notifications
You must be signed in to change notification settings - Fork 3
/
bst.py
107 lines (91 loc) · 2.13 KB
/
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
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
from primitives import BSTNode
__author__ = 'V Manikantan'
class BST:
def __init__(self):
self.root = None
def Insert(self,val):
self.root = insert(self.root,val)
def Check(self,val):
return check(self.root,val)
def Delete(self,val):
self.root = delete(self.root,val)
def Inorder(self):
inorder(self.root)
def Preorder(self):
preorder(self.root)
def Postorder(self):
postorder(self.root)
#Insert into BST.
#Takes root node and value to be inserted as parameters.
#Returns new root node.
def insert(root,val):
if(not root):
node = BSTNode(val)
return node
else:
if(val < root.value):
root.left = insert(root.left,val)
else:
root.right = insert(root.right,val)
return root
#Checks if given value exists in BST.
#Takes root node and value to be checked as parameters
#Returns True or False based on whether value exists or not
def check(root,val):
if(root):
if(root.value==val):
return True
else:
return check(root.left,val) or check(root.right,val)
else:
return False
#Deletes particular node with given value in BST, if it exists
def delete(root,val):
if(root):
if(root.value==val):
if(not root.left and not root.right):
root = None
elif(not root.left):
root = root.right
elif(not root.right):
root = root.left
else:
suc = root.left
temp = root.right
if(root.left.right==None):
root = root.left
root.right = temp
else:
while(suc.right.right):
suc = suc.right
newval = suc.right.value
suc.right = None
root.value = newval
elif(val<root.value):
root.left = delete(root.left,val)
else:
root.right = delete(root.right,val)
return root
else:
return None
#Inorder traversal of BST.
#Takes root node as parameter.
def inorder(root):
if(root):
inorder(root.left)
print root.value,
inorder(root.right)
#Preorder traversal of BST.
#Takes root node as parameter.
def preorder(root):
if(root):
print root.value,
preorder(root.left)
preorder(root.right)
#Postorder traversal of BST.
#Takes root node as parameter.
def postorder(root):
if(root):
postorder(root.left)
postorder(root.right)
print root.value,