-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathBST_All_Basic_Operation--Data_Structures
106 lines (93 loc) · 2.72 KB
/
BST_All_Basic_Operation--Data_Structures
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
import random
class Node(object):
def __init__(self,data):
self.data = data
self.left = None
self.right = None
class BST(object):
def __init__(self):
self.root = None
def insert(self,data):
if self.root is None:
self.root = Node(data)
else:
self._insert(self.root,data)
def _insert(self,cur,data):
if data < cur.data:
if cur.left is None:
cur.left = Node(data)
else:
self._insert(cur.left,data)
else:
if cur.right is None:
cur.right = Node(data)
else:
self._insert(cur.right,data)
def inorder(self):
stack = []
cur = self.root
while True:
if cur:
stack.append(cur)
cur = cur.left
elif stack:
cur = stack.pop()
print(cur.data,end = " ")
cur = cur.right
else:
break
def search(self,key):
if self.root is None:
print("Not Present")
else:
self._search(self.root,key)
def _search(self,cur,key):
if key < cur.data and cur.left is not None:
self._search(cur.left,key)
elif key > cur.data and cur.right:
self._search(cur.right,key)
if key == cur.data:
print("Found",cur.data)
def MinVal(self,node):
cur = node
while(cur.left is not None):
cur = cur.left
return cur
def delete(self,key):
if self.root is None:
return self.root
else:
self._delete(self.root,key)
def _delete(self,cur,key):
if key < cur.data:
cur.left = self._delete(cur.left,key)
elif key > cur.data:
cur.right = self._delete(cur.right,key)
else:
if cur.left is None:
temp = cur.right
cur = None
return temp
else:
temp = cur.left
cur = None
return temp
temp = self.MinVal(cur.right)
cur.data = temp.data
cur.right = self._delete(cur.right,temp.data)
return cur
def preorder(self):
stack=[]
stack.append(self.root)
while(stack):
curr = stack.pop()
print(curr.data)
if curr.right:
stack.append(curr.right)
else:
stack.append(curr.left)
bst = BST()
for i in range(1,20):
r = random.randint(1,20)
bst.insert(r)
bst.inorder()