Unit - IV
Unit - IV
CODING
EMPLOYABILITY SKILLS – I
G. Amulya,
Assistant Professor
Unit - IV
Trees and Graphs
Tree Traversals
BFS
DFS
Dijkstra's Shortest Path algorithm
Bell-man Ford Algorithm
Floyd's algorithm
Tree Traversals (Inorder)
class TreeNode:
def __init__(self, val):
self.val = val root = TreeNode(1)
self.left = None root.left = TreeNode(2)
self.right = None root.right = TreeNode(3)
def inorderTraversal(root): root.left.left = TreeNode(4)
answer = [] root.left.right = TreeNode(5)
inorderTraversalUtil(root, answer) print(inorderTraversal(root))
return answer
def inorderTraversalUtil(root, answer): Output:
if root is None: [4, 2, 5, 1, 3]
return
inorderTraversalUtil(root.left, answer)
answer.append(root.val)
inorderTraversalUtil(root.right, answer)
return
BFS
graph = {
0: [ (1, 1) ],
1: [ (0, 1), (2, 2), (3, 3) ],
2: [ (1, 2), (3, 1), (4, 5) ],
3: [ (1, 3), (2, 1), (4, 1) ],
4: [ (2, 5), (3, 1) ]
}
● A Bellman-Ford algorithm is
also guaranteed to find the
shortest path in a graph, similar
to Dijkstra’s algorithm.
● Although Bellman-Ford is
slower than Dijkstra’s algorithm,
it is capable of handling graphs
with negative edge weights,
which makes it more versatile.
from numpy import Inf
graph = {
0: [(1, 1)],
1: [(0, 1), (2, 2), (3, 3)],
2: [(1, 2), (3, 1), (4, 5)],
3: [(1, 3), (2, 1), (4, 1)],
4: [(2, -2), (3, 1)]
}
start_node=0
result = BellmanFord(graph, start_node)
for i in range(num_nodes):
for u in range(num_nodes):
for v, weight in graph[u]:
if distance[u] + weight < distance[v]:
distance[v] = distance[u] + weight
return distance
Floyd’s Algorithm
The Floyd Warshall Algorithm is for solving all pairs of shortest-path problems.
The problem is to find the shortest distances between every pair of vertices in a
given edge-weighted directed Graph. It is an algorithm for finding the shortest
path between all the pairs of vertices in a weighted graph.
nV = 4,INF = 999