-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathBinary_search_tree.py
125 lines (93 loc) · 3.1 KB
/
Binary_search_tree.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
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
''''Binary search tree python implimentation'''
class Node:
def __init__(self,item=None,left=None,right=None):
self.item=item
self.left=left
self.right=right
class BST:
def __init__(self):
self.root=None
def is_empty(self):
return self.root==None
def insert(self,data):
self.root=self.rinsert(self.root,data)
def rinsert(self,root,data):
if root is None:
return Node(data)
if data<root.item:
root.left=self.rinsert(root.left,data)
elif data>root.item:
root.right=self.rinsert(root.right,data)
return root
def search(self,data):
if not self.is_empty():
return self.rsearch(self.root,data)
else:
raise IndexError("Binary search tree is empty")
def rsearch(self,root,data):
if data==root.item:
return root
elif data<root.item:
return self.rinsert(root.left,data)
else:
return self.rsearch(root.right,data)
def inroder(self):
result=[]
self.rinorder(self.root,result)
return result
def rinorder(self,root,result):
if root:
self.rinorder(root.left,result)
result.append(root.item)
self.rinorder(root.right,result)
def preroder(self):
result=[]
self.rpreorder(self.root,result)
return result
def rpreorder(self,root,result):
if root:
result.append(root.item)
self.rpreorder(root.left,result)
self.rpreorder(root.right,result)
def postroder(self):
result=[]
self.rpostroder(self.root,result)
return result
def rpostroder(self,root,result):
if root:
self.rpostroder(root.left,result)
self.rpostroder(root.right,result)
result.append(root.item)
def find_min(self):
if not self.is_empty():
return self.inroder()[0]
else:
raise IndexError("binary search tree is empty")
def find_max(self):
if not self.is_empty():
return self.inroder()[-1]
else:
raise IndexError("binary search tree is empty")
def size(self):
if not self.is_empty():
return len(self.inroder())
else:
raise IndexError("binary search tree is empty")
def delete_node(self,data):
bst=BST()
print(bst.is_empty())
bst.insert(50)
bst.insert(30)
bst.insert(40)
bst.insert(10)
bst.insert(80)
bst.insert(70)
bst.insert(90)
print("inorder traversal of binary search tree: ",bst.inroder())
print("preorder traversal of binary search tree: ",bst.preroder())
print("postorder traversal of binary search tree: ",bst.postroder())
print(bst.is_empty())
print(bst.search(90))
print(bst.find_min())
print(bst.find_max())
print(bst.size())