Está en la página 1de 11

ESTRUCTURA DE DATOS Y ALGORITMOS

LABORATORIO N° 11
ARBOL BINARIO DE BUSQUEDA

Alumno Nota
Urquizo Apaza, Josue Alessandro
Grupo D
Fecha de Entrega 05/06/2023
Docente Renato Usnayo Cáceres

DISEÑO Y DESARROLLO DE SOFTWARE


PROGRAMA DE FORMACIÓN REGULAR
Laboratorio de Estructura de Datos y Algoritmos Página | 1

OBJETIVOS:
• Conocer, comprender y aplicar el uso de búsqueda de árboles binarios como una forma de
almacenar datos en la resolución de problemas de software.

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.

FUNDAMENTO TEÓRICO:
• Revisar el texto guía que está en el campus Virtual.

NORMAS EMPLEADAS:
• No aplica

RECURSOS:
• En este laboratorio cada alumno trabajará con un equipo con Windows 10.

METODOLOGÍA PARA EL DESARROLLO DE LA TAREA:


• El desarrollo del laboratorio es individual.

PROCEDIMIENTO:
Nota:

Las secciones en cursivas son demostrativas, pero sirven para que usted pueda instalar las
herramientas de desarrollo en un equipo externo.

EJERCICIO DE APLICACIÓN
1. Creación de un árbol binario de búsqueda

class BSTNode:
'''
Node BST definition
'''
def __init__(self, data):
self.left = None
self.right = None
self.data = data

DEPARTAMENTO DE TECNOLOGIA DIGITAL Y GESTION


Laboratorio de Estructura de Datos y Algoritmos Página | 2

Dado el árbol mostrado, hacer las modificaciones para generar un árbol binario manualmente, para
realizar búsquedas

#
# 2
# / \
# / \
# 3 4
# / \ /\
# 5 6 7 8
#

Una vez ordenado el árbol binario para búsquedas, crear el árbol con código Python

2. Búsqueda de un valor: Buscar el valor 4? , 10?

def find(root, data):


'''
Method to find data in BST
Rparam root:
:return:
'''
currentNode = root

if currentNode == None:
return None
else:
if data == currentNode.data:
return currentNode
if data < currentNode.data:
return find(currentNode.left,data)
else:
return find(currentNode.right,data)

def findIterative(root, data):


'''
Method to find data in BST
Iterative mode
:param root:
:return:
'''
currentNode = root
while currentNode:

DEPARTAMENTO DE TECNOLOGIA DIGITAL Y GESTION


Laboratorio de Estructura de Datos y Algoritmos Página | 3

if data == currentNode.data:
return currentNode
if data < currentNode.data:
currentNode = currentNode.left
else:
currentNode = currentNode.right

return None

root = BSTNode(2)
root.left = BSTNode(3)
root.right = BSTNode(4)
root.left.left = BSTNode(5)
root.left.right = BSTNode(6)
root.right.left = BSTNode(7)
root.right.right = BSTNode(8)

result_4 = find(root, 4)
if result_4:
print("El valor 4 si se pudo encontrar")
else:
print("El valor 4 no se pudo encontrar.")

result_10 = find(root, 10)


if result_10:
print("El valor 10 si se logro enconrtrar")
else:
print("El valor 10 no se pudo encontrar.")

3. Búsqueda del menor valor

def findMin(root):
'''
Find the minimum value. Recursive mode
:param root:
:return:
'''
currentNode = root
if currentNode.left == None:
return currentNode
else:
return findMin(currentNode.left)

def findMinIterative(root):
'''
Find the minimum value. Iterative mode
:param root:

DEPARTAMENTO DE TECNOLOGIA DIGITAL Y GESTION


Laboratorio de Estructura de Datos y Algoritmos Página | 4

:return:
'''
currentNode = root
while currentNode.left != None:
currentNode = currentNode.left
return currentNode

4. Búsqueda del mayor valor

def findMax(root):
'''
Find the maximum value. Recursive mode
:param root:
:return:
'''
currentNode = root
if currentNode.right == None:
return currentNode
else:
return findMax(currentNode.right)

def findMaxIterative(root):
'''
Find the maximum value. Iterative mode
:param root:
:return:
'''
currentNode = root
while currentNode.right != None:
currentNode = currentNode.right
return currentNode

Tarea

• Implementa un método que devuelva el número de hojas del árbol.


def count_leaves(self):
if self.left is None and self.right is None: # Es una hoja
return 1

count = 0

if self.left is not None:


count += self.left.count_leaves()

if self.right is not None:


count += self.right.count_leaves()

return count

DEPARTAMENTO DE TECNOLOGIA DIGITAL Y GESTION


Laboratorio de Estructura de Datos y Algoritmos Página | 5

root = BSTNode(2)
root.left = BSTNode(3)
root.right = BSTNode(4)
root.left.left = BSTNode(5)
root.left.right = BSTNode(6)
root.right.left = BSTNode(7)
root.right.right = BSTNode(8)

leaf_count = root.count_leaves()
print("El número de hojas es: ", leaf_count)

O
def num_leaves(self):
def _num_leaves(node):
if node is None:
return 0
if node.left is None and node.right is None:
return 1
return _num_leaves(node.left) + _num_leaves(node.right)

return _num_leaves(self)

• Implementa un método que devuelva el número de nodos internos del árbol.


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

def count_internal_nodes(self):
if self.left is None and self.right is None: # Es una hoja
return 0

count = 1

if self.left is not None:


count += self.left.count_internal_nodes()

if self.right is not None:


count += self.right.count_internal_nodes()

return count

root = BSTNode(2)
root.left = BSTNode(3)
root.right = BSTNode(4)
root.left.left = BSTNode(5)
root.left.right = BSTNode(6)
root.right.left = BSTNode(7)
root.right.right = BSTNode(8)

internal_node_count = root.count_internal_nodes()
print("El número de nodos internos es: ", internal_node_count)

DEPARTAMENTO DE TECNOLOGIA DIGITAL Y GESTION


Laboratorio de Estructura de Datos y Algoritmos Página | 6

O
def num_internal_nodes(self):
def _num_internal_nodes(node):
if node is None or (
node.left is None and node.right is None):
return 0
return 1 + _num_internal_nodes(node.left) + _num_internal_nodes(
node.right)

return _num_internal_nodes(self)

• Implementa un método que devuelva la distancia entre la raíz del árbol y un nodo dado.
def distance_to_root(self, target_node):
return self._distance_to_root_helper(self, target_node)

def _distance_to_root_helper(self, current_node, target_node,


distance=0):
if current_node is None:
return -1

if current_node == target_node:
return distance

left_distance = self._distance_to_root_helper(current_node.left,
target_node, distance + 1)
if left_distance != -1:
return left_distance

right_distance = self._distance_to_root_helper(current_node.right,
target_node, distance + 1)
if right_distance != -1:
return right_distance

return -1

root = BSTNode(2)
root.left = BSTNode(3)
root.right = BSTNode(4)
root.left.left = BSTNode(5)
root.left.right = BSTNode(6)
root.right.left = BSTNode(7)
root.right.right = BSTNode(8)

target_node = root.left.right

distance = root.distance_to_root(target_node)
print("La distancia entre la raiz y el nodo", target_node.data, "es:",
distance)

DEPARTAMENTO DE TECNOLOGIA DIGITAL Y GESTION


Laboratorio de Estructura de Datos y Algoritmos Página | 7

def distance_to_root(self, node):


def _distance_to_root(curr_node):
if curr_node == node:
return 0
if curr_node is None:
return float("inf")
return 1 + min(_distance_to_root(curr_node.left),
_distance_to_root(curr_node.right))

return _distance_to_root(self)
• Implementa un método que compruebe si un árbol binario de búsqueda está equilibrado.
def is_balanced(self):
def _get_height(node):
if node is None:
return 0
left_height = _get_height(node.left)
right_height = _get_height(node.right)
return max(left_height, right_height) + 1

def _is_balanced_helper(node):
if node is None:
return True
left_height = _get_height(node.left)
right_height = _get_height(node.right)
if abs(left_height - right_height) > 1:
return False
return _is_balanced_helper(node.left) and
_is_balanced_helper(node.right)

return _is_balanced_helper(self)
root = BSTNode(2)
root.left = BSTNode(3)
root.right = BSTNode(4)
root.left.left = BSTNode(5)
root.left.right = BSTNode(6)
root.right.left = BSTNode(7)
root.right.right = BSTNode(8)

balanced = root.is_balanced()
if balanced:
print("El árbol si está equilibrado.")
else:
print("El árbol no está equilibrado.")

O
def is_balanced(self):
def _is_balanced(node):
if node is None:
return True
left_height = self._tree_height(node.left)

DEPARTAMENTO DE TECNOLOGIA DIGITAL Y GESTION


Laboratorio de Estructura de Datos y Algoritmos Página | 8

right_height = self._tree_height(node.right)
if abs(left_height - right_height) > 1:
return False
return _is_balanced(node.left) and _is_balanced(node.right)

return _is_balanced(self)

def _tree_height(self, node):


if node is None:
return -1
return 1 + max(self._tree_height(node.left),
self._tree_height(node.right))
• Implementa un método que compruebe si dos árboles binarios de búsqueda son iguales.
def is_equal(self, other_tree):
def _is_equal_helper(node1, node2):
if node1 is None and node2 is None:
return True
if node1 is None or node2 is None:
return False
if node1.data != node2.data:
return False
return _is_equal_helper(node1.left, node2.left) and
_is_equal_helper(node1.right, node2.right)

return _is_equal_helper(self, other_tree)

root1 = BSTNode(2)
root1.left = BSTNode(3)
root1.right = BSTNode(4)
root1.left.left = BSTNode(5)
root1.left.right = BSTNode(6)
root1.right.left = BSTNode(7)
root1.right.right = BSTNode(8)

root2 = BSTNode(2)
root2.left = BSTNode(3)
root2.right = BSTNode(4)
root2.left.left = BSTNode(5)
root2.left.right = BSTNode(6)
root2.right.left = BSTNode(7)
root2.right.right = BSTNode(8)

if root1.is_equal(root2):
print("Los árboles son iguales.")
else:
print("Los árboles no son iguales.")

O
def is_equal(self, other_tree):
def _is_equal(node1, node2):
if not node1 and not node2:
return True

DEPARTAMENTO DE TECNOLOGIA DIGITAL Y GESTION


Laboratorio de Estructura de Datos y Algoritmos Página | 9

if not node1 or not node2:


return False
if node1.data != node2.data:
return False
return _is_equal(node1.left, node2.left) and _is_equal(node1.right,
node2.right)

return _is_equal(self, other_tree)


Adjuntar capturas importantes del código así como su ejecución y el código en un zip, rar, Google drive o
git

DEPARTAMENTO DE TECNOLOGIA DIGITAL Y GESTION


Laboratorio de Estructura de Datos y Algoritmos Página | 10

OBSERVACIONES:
1. Los árboles binarios de búsqueda son estructuras de datos utilizadas para almacenar y organizar
información en forma de un árbol.
2. Cada nodo en un árbol binario de búsqueda tiene un valor único y dos hijos, uno izquierdo y otro
derecho, y solo puede haber un nodo con un valor determinado en el árbol.
3. Los valores de los nodos en el subárbol izquierdo de un nodo dado son menores que el valor del
nodo, mientras que los valores en el subárbol derecho son mayores.
4. La altura de un árbol binario de búsqueda puede variar ampliamente según el número y la
organización de los nodos en el árbol.
5. Con los árboles binarios podemos agregar y quitar valores de una manera mas rápida.

CONCLUSIONES:

1. Los árboles binarios de búsqueda son útiles para mantener la información de manera organizada
y permiten un acceso rápido a los valores almacenados.
2. La velocidad de búsqueda en un árbol binario de búsqueda es O(log n), lo que hace que sea
muy eficiente para un gran número de valores.
3. La forma en que se insertan los valores en un árbol binario de búsqueda puede afectar
significativamente la altura del árbol y, por lo tanto, su eficiencia.
4. Los árboles binarios de búsqueda son adecuados para problemas de búsqueda en los que la
ordenación de los valores es importante.
5. Los árboles binarios tiene varias extensiones, como base de datos, procedimientos de búsqueda
y base para la creación de juegos y graficos.

DEPARTAMENTO DE TECNOLOGIA DIGITAL Y GESTION

También podría gustarte