Documentos de Académico
Documentos de Profesional
Documentos de Cultura
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
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.
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
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
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)
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.")
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:
:return:
'''
currentNode = root
while currentNode.left != None:
currentNode = currentNode.left
return currentNode
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
count = 0
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)
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)
def count_internal_nodes(self):
if self.left is None and self.right is None: # Es una hoja
return 0
count = 1
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)
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)
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)
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)
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)
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
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.