Skip to content
Snippets Groups Projects
Commit 66b020fe authored by Chianc Leocádio de Lima's avatar Chianc Leocádio de Lima
Browse files

arvore binaria com nós

parent 87f3c070
No related branches found
No related tags found
No related merge requests found
class Node:
def __init__(self, data=None, father = None, left = None, right = None):
self.data = data
self.father = father
self.left = left
self.right = right
#____________________________________________________________________________#
def insert(data, father):
filho = Node(data, father)
if father.left == None:
father.left = filho
return True
elif father.left != None and father.right == None:
father.right = filho
return True
else:
return False
#____________________________________________________________________________#
def searchPre(data, root):
if root == None:
return None
if root.data == data:
return root
else:
return searchPre(data, root.left) or searchPre(data, root.right)
#____________________________________________________________________________#
def remove(root):
aRemover = root
if aRemover.left == None and aRemover.right == None:
if aRemover.father.left == aRemover:
aRemover.father.left = None
aRemover = None
return True
else:
aRemover.father.right = None
aRemover = None
return True
elif aRemover.left == None or aRemover.right == None:
if aRemover.left == None:
aRemover.right.father = aRemover.father
aRemover = aRemover.right
aRemover.right = None
return True
else:
aRemover.left.father = aRemover.father
aRemover = aRemover.left
aRemover.left = None
return True
else:
substituto = aRemover
while substituto.left != None and substituto.right != None:
substituto = substituto.left
substituto.father.left = None
substituto = aRemover
return True
#__________________________________________________________________________________#
def showTree(root):
if root:
print(root.data)
showTree(root.left)
showTree(root.right)
#____________________________________________________________________________________#
a = Node(0)
#formas de inserir os nós
insert(2, a)
insert(5, a)
a.left.left = Node(6, a.left)
a.right.right = Node(7, a.right)
insert(4, a.left)
insert(3, a.right)
#mostrar os nós da árvore
showTree(a)
print(searchPre(4,a)) #retorna o objeto
print(remove(searchPre(4,a))) #remove o objeto encontrado na busca (print "True" qdo remove)
print(searchPre(4,a)) #retorna None
#mostrar os nós da árvore, agora sem o nó removido
showTree(a)
\ No newline at end of file
0% Loading or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment