Q1/
class Node:
def __init__(self, data):
self.data = data
self.left_child = None
self.right_child = None
def dfs_search(start_node, search_value):
stack = [start_node]
while stack:
current_node = stack.pop()
if current_node.data == search_value:
return True
if current_node.right_child:
stack.append(current_node.right_child)
if current_node.left_child:
stack.append(current_node.left_child)
return False
# Initialize the binary tree
root_node = Node(50)
root_node.left_child = Node(20)
root_node.left_child.left_child = Node(11)
root_node.left_child.right_child = Node(15)
root_node.right_child = Node(45)
root_node.right_child.left_child = Node(30)
root_node.right_child.right_child = Node(78)
# Continuously search for a value in the binary tree
while True:
search_value = int(input("Enter the number to search: "))
if dfs_search(root_node, search_value):
print(f"Number {search_value} is found in the tree.")
else:
print(f"Number {search_value} is not found in the tree.")
break # Exit the loop if the number is not found in the tree
Q/2
from queue import PriorityQueue
def ucs(start_point, end_point, network):
queue = PriorityQueue()
queue.put((0, start_point))
distances = {node: float('inf') for node in network}
distances[start_point] = 0
parents_map = {}
while not queue.empty():
current_distance, current_node = queue.get()
if current_node == end_point:
path = []
while current_node != start_point:
path.append(current_node)
current_node = parents_map[current_node]
path.append(start_point)
return list(reversed(path))
if current_distance > distances[current_node]:
continue
for adjacent, travel_cost in network[current_node].items():
new_distance = current_distance + travel_cost
if new_distance < distances[adjacent]:
distances[adjacent] = new_distance
queue.put((new_distance, adjacent))
parents_map[adjacent] = current_node
return "Failure: No path found."
# Define the graph
network = {
'A': {'B': 1, 'D': 1},
'B': {'C': 1, 'D': 1},
'C': {'E': 1},
'D': {'E': 1},
'E': {}
}
# Find the path using uniform cost search
path_to_goal = ucs('A', 'E', network)
print("Path from A to E:", path_to_goal)