-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain.py
More file actions
298 lines (214 loc) · 7.19 KB
/
Copy pathmain.py
File metadata and controls
298 lines (214 loc) · 7.19 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
import sys
import copy
class Node:
def __init__(self, key):
self.left = None
self.right = None
self.left_nodes = 0
self.right_nodes = 0
self.data = key
def busca_binaria(root, value):
if not root:
return False
if root.data == value:
return True
elif root.data > value:
return busca_binaria(root.right, value)
else:
return busca_binaria(root.left, value)
def remover_no(root, data):
if not root:
return None
if data < root.data:
root.left = remover_no(root.left, data)
elif data > root.data:
root.right = remover_no(root.right, data)
else:
if root.left is None and root.right is None:
root = None
elif root.left is None:
temp = root
root = root.right
elif root.right is None:
temp = root
root = root.left
else:
temp = min_value(root, root.right)
root.data = temp.data
root.right = remover_no(root.right, temp.data)
return root
def min_value(root, node):
if root == None:
print("Árvore vazia!")
else:
while(node.left != None):
node = node.left
return (node)
def insira(root, node):
exists = True
if root.data == node.data:
print(f'>>> ERRO: O valor {node.data} não pôde ser adicionado pois já existe na árvore.')
return False
elif root.data < node.data:
if root.right is None:
root.right = node
else:
exists = insira(root.right, node)
if exists: root.right_nodes += 1
return exists
else:
if root.left is None:
root.left = node
else:
exists = insira(root.left, node)
if exists: root.left_nodes += 1
return exists
def atualiza_nos(root):
root.left_nodes = 0
root.right_nodes = 0
if root.right:
root.right_nodes += atualiza_nos(root.right)
if root.left:
root.left_nodes += atualiza_nos(root.left)
return root.left_nodes + root.right_nodes + 1
def get_height(node):
if not node:
return 0
if node.left and node.right:
return 1 + max(get_height(node.left), get_height(node.right))
elif node.left:
return 1 + get_height(node.left)
elif node.right:
return 1 + get_height(node.right)
else:
return 1
def enesimo_elemento(root, n):
size = root.left_nodes + root.right_nodes + 1
if not root or n <= 0 or n > size:
return None
if n <= root.left_nodes:
return enesimo_elemento(root.left, n)
elif n == root.left_nodes + 1:
return root
else:
return enesimo_elemento(root.right, n - root.left_nodes - 1)
def posicao(root, x):
current = root
s = []
done = 0
count = 1
while(not done):
if current is not None:
s.append(current)
current = current.left
else:
if(len(s) > 0):
current = s.pop()
if current.data == x:
return count
current = current.right
count += 1
else:
done = 1
return 0
def mediana(root):
size = root.left_nodes + root.right_nodes + 1
med = 0
if size % 2 == 0:
med = size // 2
else:
med = (size // 2) + 1
return enesimo_elemento(root, med).data
def eh_cheia(root):
h = get_height(root)
size = root.left_nodes + root.right_nodes + 1
return size == ((2 ** h) - 1)
def eh_completa(root, index, n_nodes):
if root is None:
return True
if index >= n_nodes :
return False
return (eh_completa(root.left , 2*index+1, n_nodes)
and eh_completa(root.right, 2*index+2, n_nodes))
def to_string(root):
if not root:
return
queue = []
queue.append(root)
while len(queue) > 0:
print(queue[0].data, end=' ')
node = queue.pop(0)
if node.left:
queue.append(node.left)
if node.right:
queue.append(node.right)
print("")
def inserir(root, nodes):
for node in nodes:
insira(root, node)
if __name__ == "__main__":
if len(sys.argv) < 3:
print("Número inválido de argumentos!")
exit()
inputs = open(sys.argv[1], "r")
#checks if the first entry are the values to insert on tree
string = str(inputs.readline().split(' ')[0])
if not string.isdigit():
print(">>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>> ERRO <<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<")
print("O primeiro arquivo deve conter os valores a serem inseridos na árvore.\nVerifique a entrada!")
exit()
#returns to the beginning of the buffer
inputs.seek(0)
#reads all the values
values = list(map(int, inputs.readline().split(' ')))
root = Node(values.pop(0))
nodes = [Node(value) for value in values]
#inserts all the values on the tree
inserir(root, nodes)
print()
commands = open(sys.argv[2], "r")
for index, command in enumerate(commands):
command_, argument = command.replace('\n', ' ').split(' ', 1)
print(f'============ COMANDO: {command_} - Argumento(s): {argument}=============')
if command_ == 'ENESIMO':
no = enesimo_elemento(root, int(argument))
if no:
print(f'Elemento na posição {argument} -> {no.data}')
else:
print(f'>>> ERRO: A arvore não possui um {argument}° elemento')
elif command_ == 'POSICAO':
position = posicao(root, int(argument))
if position:
print(f'Posição do elemento {argument} -> {position}')
else:
print(f'>>> ERRO: O elemento {int(argument)} não está na árvore.')
elif command_ == 'MEDIANA':
print(f'Elemento da posição mediana -> {mediana(root)}')
elif command_ == 'CHEIA':
print(f'Árvore é cheia? -> {eh_cheia(root)}')
elif command_ == 'COMPLETA':
n_nodes = root.left_nodes + root.right_nodes + 1
print(f'Árvore é completa? -> {eh_completa(root, 0, n_nodes)}')
elif command_ == 'IMPRIMA':
print('Valores da árvore por níveis:')
to_string(root)
elif command_ == 'INSIRA':
flag = insira(root, Node(int(argument)))
if flag:
print(f'O valor {argument} foi adicionado!')
elif command_ == 'REMOVA':
aux = copy.copy(root)
root = remover_no(root, int(argument))
atualiza_nos(root)
if (aux.left_nodes + aux.right_nodes) == (root.left_nodes + root.right_nodes):
print(f'>>> ERRO: O valor {argument} não existe na árvore')
else:
print(f'O valor {argument} foi removido com sucesso!')
elif command_ == 'BUSCA':
flag = busca_binaria(root, int(argument))
if flag:
print(f'O valor {argument} se encontra na árvore.')
else:
print(f'O valor {argument} NÃO encontra na árvore.')
else:
print('Nenhum comando correspondente encontrado!')