-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathrbtree.py
More file actions
314 lines (276 loc) · 6.76 KB
/
rbtree.py
File metadata and controls
314 lines (276 loc) · 6.76 KB
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
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
class node():
def __init__(self, val, black=False, parent=None, left=None, right=None):
self.val = val
self.black = black
self.parent = parent
self.left = left
self.right = right
def isLeftChild(self):
if self.parent == None:
return False
return self.parent.left == self
def sibling(self):
if self.parent == None:
return None
if self.parent.left == self:
return self.parent.right
else:
return self.parent.left
def uncle(self):
if self.parent == None:
return None
return self.parent.sibling()
def grandparent(self):
if self.parent == None or self.parent.parent == None:
return None
return self.parent.parent
def flipColor(self):
self.black = not self.black
def swapChild(self, n, x):
if self.left == n:
self.left = x
else:
self.right = x
def successor(self, val):
pass
def predecessor(self, val):
pass
def __repr__(self):
COLR = 'B' if self.black else 'R'
out = "{}{}".format(COLR, self.val) if False else self.__str__()
return out
def __str__(self):
COLR = '\33[90m' if self.black else '\033[91m'
CEND = '\033[0m'
return "{}{}{}".format(COLR, self.val, CEND)
class rbTree():
def __init__(self):
self.root = None
self.sentinel = node('S', black=True)
def insert(self, val):
x = node(val, left=self.sentinel, right=self.sentinel)
if self.root == None:
x.black = True
self.root = x
return
else:
current = self.root
while True:
if current.val == val:
return
elif current.val > val:
if current.left == self.sentinel:
current.left = x
x.parent = current
break
else:
current = current.left
continue
elif current.val < val:
if current.right == self.sentinel:
current.right = x
x.parent = current
break
else:
current = current.right
continue
self.fixRedBlack(x)
def fixRedBlack(self, n):
# print("FIXREDBLACK\nn is {}".format(n))
while n != self.root and n.parent.black != True:
# if n.black:
# return
if n.parent == n.parent.parent.left:
# parent is to the left
# print("CASE A")
u = n.parent.parent.right
# print("u is {} and is right".format(u))
if not u.black:
# case 1 -> change the colors
n.parent.black = True
u.black = True
if n.parent.parent != None:
n.parent.parent.black = False
# move x up the tree
# print("CASE 1: n{} p{} u{}".format(n, p, u))
n = n.parent.parent
else:
# uncle is black
if n == n.parent.right:
# and n is to the right
# case 2 -> move n up and rotate
n = n.parent
self.rotateLeft(n)
# case 3
n.parent.black = True
if n.parent.parent != None:
n.parent.parent.black = False
self.rotateRight(n.parent.parent)
else:
u = n.parent.parent.left
if not u.black:
# case 1 -> change the colors
n.parent.black = True
u.black = True
if n.parent.parent != None:
n.parent.parent.black = False
# move x up the tree
n = n.parent.parent
else:
# uncle is black
if n == n.parent.left:
# and n is to the right
# case 2 -> move n up and rotate
n = n.parent
self.rotateRight(n)
# case 3
n.parent.black = True
if n.parent.parent != None:
n.parent.parent.black = False
self.rotateLeft(n.parent.parent)
self.root.black = True
def delete(self, val):
pass
def find(self, val):
current = self.root
while True:
if current.val == val:
return current
elif current.val < val:
if current.right == self.sentinel:
return None
else:
current = current.right
continue
elif current.val > val:
if current.left == self.sentinel:
return None
else:
current = current.left
continue
def rotateRight(self, n):
if n == None:
return
l = n.left
if l == self.sentinel:
return
p = n.parent
if p != None:
p.swapChild(n, l)
else:
self.root = l
l.parent = p
n.parent = l
lr = l.right
l.right = n
n.left = lr
if lr != None:
lr.parent = n
def rotateLeft(self, n):
if n == None:
return
r = n.right
if r == self.sentinel:
return
p = n.parent
if p != None:
p.swapChild(n, r)
else:
self.root = r
r.parent = p
n.parent = r
rl = r.left
r.left = n
n.right = rl
if rl != None:
rl.parent = n
def min(self):
pass
def max(self):
pass
def inOrderTraverse(self):
def dp(x):
out = ''
if x != self.sentinel:
out += dp(x.left)
out += x.__repr__() + " "
out += dp(x.right)
return out
return dp(self.root)
def asciiTree(self):
def dp(x):
out = ''
if x == None:
return out
leftConnector = '|' if (not x.isLeftChild() and x.parent != None) else ' '
rightConnector = '|' if x.isLeftChild() else ' '
prefix = ""
if x.parent != None:
prefix = "L-" if x.isLeftChild() else "R-"
if x == self.sentinel:
prefix = ""
childPad = " " * (len(str(x.val)) + len(prefix))
leftOut = dp(x.left)
leftOut = [ "{}{}{}\n".format(leftConnector,childPad,l) for l in leftOut.split('\n') if l != '']
out += ''.join(leftOut)
out += prefix + x.__repr__() + '\n'
rightOut = dp(x.right)
rightOut = [ "{}{}{}\n".format(rightConnector,childPad,l) for l in rightOut.split('\n') if l != '']
out += ''.join(rightOut)
return out
return dp(self.root)
if __name__ == "__main__":
A =[
[32, 7, 17, 24, 75, 100, 111, 101, 102, 2, 3, 204, 55, 66, 60, 11, 33, 34 ],
[7,56,88,64,667,97,986,5,44,768,547,876,767,222,333,444,555,434,91,723,575,845,253,111,20,672,785,693,822,389,797,123,4444,37,100,101,209,917,888,778,887,234,345,456,567,677,789,879,987,876,765,654,543,432,321,132],
[1,2,3,4,5],
]
R = [
[],
[],
[]
]
S = [
[100, 66, 11, 32, 204, 2],
[7, 88,456,987,666,797,243,222,111,100,5,876,777],
[1,4,5,3,2],
]
for i in range(len(A)):
#Build tree
print("Building tree with {}".format(A[i]))
t = rbTree()
for ai in range(0, len(A[i])):
t.insert(A[i][ai])
#Find elements
for f in S[i]:
print("t.find({}) = {}".format(f, t.find(f)))
#Get successor
# for s in S[i]:
# sf = t.find(s)
# if sf != None:
# print("t.successor({}) = {}".format(s, sf.successor()))
# else:
# print("t.successor({}) = {}".format(s, None))
#Get predecessor
# for p in S[i]:
# pf = t.find(p)
# if pf != None:
# print("t.predecessor({}) = {}".format(p, pf.predecessor()))
# else:
# print("t.predecessor({}) = {}".format(p, None))
#Traverse
print(t.inOrderTraverse())
print(t.asciiTree())
# print('min = {}'.format(t.min()))
# print('max = {}'.format(t.max()))
#Delete elements
# for d in S[i]:
# df = t.find(d)
# if df != None:
# t.delete(df)
# print("t.delete({})".format(d))
# else:
# print("{} not found in t".format(d))
#Traverse
# t.inOrderTraverse()
# t.asciiTree()