Está en la página 1de 12

Laboratorio de Algoritmos y Estructuras de Datos

Página 2 de 2

Alumno(s) Nota

Yaguno Huamaní Ángel Eduardo

Grupo B
Ciclo III
Fecha de entrega 22/10/2023
Laboratorio de Algoritmos y Estructuras de Datos
Página 1 de 2

I.- OBJETIVOS:
● Implementar recorridos en árboles binarios
● Realizar operaciones en recorridos de árboles binarios.

II.- SEGURIDAD:
Advertencia:
En este laboratorio está prohibida la manipulación del
hardware, conexiones eléctricas o de red; así como la
ingestión de alimentos o bebidas.

III.- FUNDAMENTO TEÓRICO:


● Revisar el texto guía que está en el campus Virtual.

IV.- NORMAS EMPLEADAS:


● No aplica

V.- RECURSOS:
● En este laboratorio cada alumno trabajará con un equipo con Windows 10.

VI.- METODOLOGÍA PARA EL DESARROLLO DE LA TAREA:


● El desarrollo del laboratorio es individual.

VII.- PROCEDIMIENTO:

1. Recorridos de arboles binarios

- Pre Order Traversal. ( PreOrderTraversal.py). 🡺 D.L.R.

'''
Created on Mar 11, 2019
@author: jgomezm
@version: 1.2 April 29,2020
'''
class BinaryTreeNode:

def __init__(self, data, left = None, right = None):


self.data = data # value node
self.left = left # left child
self.right = right # right child

# Pre-order recursivc traversal.


# The nodes' values are appended to
# the result list in traversal order
def preOrderRecursive(root, result):

if not root:
return

result.append(root.data)
preOrderRecursive(root.left, result)
preOrderRecursive(root.right, result)

'''
Binary Tree

Estudiante
Laboratorio de Algoritmos y Estructuras de Datos
Página 2 de 2

|
----------------------
| |
Aprobado Desaprobado

'''

childrenLeft = BinaryTreeNode("Aprobado")
childrenRight = BinaryTreeNode("Desaprobado")
root = BinaryTreeNode("Estudiante",childrenLeft,childrenRight)

result = []
preOrderRecursive(root, result)
print(result)

- In Order Traversal. ( InOrderTraversal.py). 🡺 L.D.R.

'''
Created on Mar 11, 2019
@author: jgomezm
@version: 1.2 April 29,2020
'''
class BinaryTreeNode:

def __init__(self, data, left = None, right = None):


self.data = data # value node
self.left = left # left child
self.right = right # right child

# In-order recursive traversal. The


# nodes' values are appended to the
# result list in traversal order
def inOrderRecursive(root, result):

if not root:
return

inOrderRecursive(root.left, result)
result.append(root.data)
inOrderRecursive(root.right, result)

'''
Binary Tree

Estudiante
|
----------------------
| |
Aprobado Desaprobado

'''

childrenLeft = BinaryTreeNode("Aprobado")
childrenRight = BinaryTreeNode("Desaprobado")
root = BinaryTreeNode("Estudiante",childrenLeft,childrenRight)

result = []
inOrderRecursive(root, result)
print(result)
Laboratorio de Algoritmos y Estructuras de Datos
Página 3 de 2

- Post Order Traversal. ( PostOrderTraversal.py) 🡺 L.R.D.

'''
Created on Mar 11, 2019
@author: jgomezm
@version: 1.2 April 29,2020
'''
class BinaryTreeNode:

def __init__(self, data, left = None, right = None):


self.data = data # value node
self.left = left # left child
self.right = right # right child

# Post-order recursive traversal. The


# nodes' values are appended to the
# result list in traversal order
def postOrderRecursive(root, result):

if not root:
return

postOrderRecursive(root.left, result)
postOrderRecursive(root.right, result)
result.append(root.data)

'''
Binary Tree

Estudiante
|
----------------------
| |
Aprobado Desaprobado

'''

childrenLeft = BinaryTreeNode("Aprobado")
childrenRight = BinaryTreeNode("Desaprobado")

root = BinaryTreeNode("Estudiante",childrenLeft,childrenRight)

result = []
postOrderRecursive(root, result)
print(result)

Ejercicios : Construir los árboles propuesta y su recorrido indicado.

'''
Binary Tree : Preorder Traversal

1
|
----------------------
| |
2 3
| |
---------- ------------
Laboratorio de Algoritmos y Estructuras de Datos
Página 4 de 2

| | | |
4 5 6 7

--> 1 2 4 5 3 6 7
'''
childrenLeft = BinaryTreeNode(2)
childrenRight = BinaryTreeNode(3)
tree = BinaryTreeNode(1, childrenLeft, childrenRight)

childrenLeft.left = BinaryTreeNode(4)
childrenLeft.right = BinaryTreeNode(5)

childrenRight.left = BinaryTreeNode(6)
childrenRight.right = BinaryTreeNode(7)

result = []
preOrderRecursive(tree, result)
print(result)

'''
Binary Tree : Inorder Traversal

1
|
----------------------
| |
2 3
| |
---------- ------------
| | | |
4 5 6 7

--> 4 2 5 1 6 3 7
'''

result2 = []
inOrderRecursive(tree, result2)
print(result2)
[4, 2, 5, 1, 6, 3, 7]

'''
Binary Tree : Postorder Traversal

1
|
----------------------
| |
2 3
| |
Laboratorio de Algoritmos y Estructuras de Datos
Página 5 de 2

---------- ------------
| | | |
4 5 6 7

--> 4 5 2 6 7 3 1
'''
result3 = []
postOrderRecursive(tree, result3)
print(result3)
[4, 5, 2, 6, 7, 3, 1]

2. Encontrar el valor máximo y mínimo de un árbol

'''
Created on Mar 11, 2019
@author: jgomezm
@version: 1.2 April 29,2020
'''
class BinaryTreeNode:

def __init__(self, data, left = None, right = None):


self.data = data # value node
self.left = left # left child
self.right = right # right child

def findMaxRecursive(tree):

# Base case
if tree is None:
return float('-inf') # Mininum value

data = tree.data
left_max = findMaxRecursive(tree.left)
right_max = findMaxRecursive(tree.right)

return max([data, left_max, right_max])

'''
Binary Tree

1
|
----------------------
| |
2 3

'''

childrenLeft = BinaryTreeNode(2)
childrenRight = BinaryTreeNode(3)
root = BinaryTreeNode(1,childrenLeft,childrenRight)

maxData = findMaxRecursive(root)
print(maxData)
Laboratorio de Algoritmos y Estructuras de Datos
Página 6 de 2

En el siguiente ejercicio , construir el arbol y encontrar el máximo y minimo valor

3. Encontrar un valor en un árbol (este ejercicio necesita la clase BinaryTreeNode)

'''
Created on Mar 11, 2019
@author: jgomezm
@version: 1.2 April 29,2020
'''
class BinaryTreeNode:

def __init__(self, data, left = None, right = None):


self.data = data # value node
self.left = left # left child
self.right = right # right child

#
def findDataRecursive(root, dataSearch, nro_times=0):

if root == None:
return nro_times

tmp_nro_times = nro_times

if root.data == dataSearch:
tmp_nro_times +=1

return tmp_nro_times + \
findDataRecursive(root.left, dataSearch, nro_times) + \
findDataRecursive(root.right, dataSearch, nro_times)

#
#
# Resolution
# 1
# 2 3
# 7 5 6 7

root = BinaryTreeNode(1)
root.left = BinaryTreeNode(2)
Laboratorio de Algoritmos y Estructuras de Datos
Página 7 de 2

root.right = BinaryTreeNode(3)
root.left.left = BinaryTreeNode(7)
root.left.right = BinaryTreeNode(5)
root.right.left = BinaryTreeNode(6)
root.right.right = BinaryTreeNode(7)

dataSearch = 7
nro_times = findDataRecursive(root, dataSearch)
print("Se encontro el valor de %d, %d veces" % (dataSearch, nro_times))

- Buscar el número 10 ¿Lo encuentra? ¿Qué devuelve la función de búsqueda?


No se encuentra el valor del número 10, devuelve que se ha encontrado 0 veces

4. Calcular la suma de datos de un árbol (este ejercicio necesita la clase BinaryTreeNode)

def sumRecursive(root):
if (root == None):
return 0
return root.data + \
sumRecursive(root.left) + \
sumRecursive(root.right)

#
# Resolution
# 1
# 2 3
# 7 5 6 7

root = BinaryTreeNode(1)
root.left = BinaryTreeNode(2)
root.right = BinaryTreeNode(3)
root.left.left = BinaryTreeNode(7)
root.left.right = BinaryTreeNode(5)
root.right.left = BinaryTreeNode(6)
root.right.right = BinaryTreeNode(7)

tmp = sumRecursive(root)
print("La suma del arbol es %d" % (tmp))

Ejercicios propuestos: para el árbol dado :

#
# Resolution
# 1
# 2 3
# 7 5 6 7

- Calcular la suma de los números pares de árbol siguiente


def sumEvenNumbers(root):
if root is None:
Laboratorio de Algoritmos y Estructuras de Datos
Página 8 de 2

return 0

current_sum = 0
if root.data % 2 == 0:
current_sum = root.data
return current_sum + sumEvenNumbers(root.left) +
sumEvenNumbers(root.right)
# Árbol:
# 1
# 2 3
# 7 5 6 7
root = BinaryTreeNode(1)
root.left = BinaryTreeNode(2)
root.right = BinaryTreeNode(3)
root.left.left = BinaryTreeNode(7)
root.left.right = BinaryTreeNode(5)
root.right.left = BinaryTreeNode(6)
root.right.right = BinaryTreeNode(7)

even_sum = sumEvenNumbers(root)
print("La suma de los números pares en el árbol es:",
even_sum)

- Calcular la suma de los elementos que están en los nodos izquierdos. No considerar la raíz
principal como un elemento que esta a la izquierda.
def sumLeftNodes(root):
if root is None or (root.left is None and root.right is
None):
return 0
Laboratorio de Algoritmos y Estructuras de Datos
Página 9 de 2

left_sum = 0
if root.left:
left_sum += root.left.data
return left_sum + sumLeftNodes(root.left) +
sumLeftNodes(root.right)
# Árbol:
# 1
# 2 3
# 7 5 6 7
root = BinaryTreeNode(1)
root.left = BinaryTreeNode(2)
root.right = BinaryTreeNode(3)
root.left.left = BinaryTreeNode(7)
root.left.right = BinaryTreeNode(5)
root.right.left = BinaryTreeNode(6)
root.right.right = BinaryTreeNode(7)

left_nodes_sum = sumLeftNodes(root)
print("La suma de los elementos en los nodos izquierdos es:",
left_nodes_sum)

CONCLUSIONES:
1. Los recorridos en árboles binarios, como Preorder, Inorder y Postorder, son
técnicas fundamentales para explorar y procesar los elementos de un árbol
de manera específica. Cada uno de estos recorridos tiene su propio
propósito y aplicaciones.
2. La búsqueda de un valor en un árbol y la suma de elementos son
operaciones comunes que se pueden realizar en árboles binarios. Se
pueden implementar de manera recursiva, visitando nodos en un orden
particular.
Laboratorio de Algoritmos y Estructuras de Datos
Página 10 de 2

3. La manipulación de árboles binarios implica comprender cómo se


estructuran y organizan los nodos en el árbol. Las operaciones que
realizamos en un árbol dependen de la tarea que queramos llevar a cabo.

También podría gustarte