DSD Lab Manual
DSD Lab Manual
Aim:
To write a Python program for inorder traverse to search element from binary tree.
Algorithm:
1. Create a binary tree.
2. Initially all the left and right vertex are None, then declare the values using
insert() function.
def__init__(self, data):
self.left = None
self.right = None
self.data = data
# Insert Node
if self.data:
if data<self.data:
if self.left is None:
self.left = Node(data)
else:
self.left.insert(data)
elif data>self.data:
if self.right is None:
self.right = Node(data)
else:
self.right.insert(data)
else:
self.data = data
def PrintTree(self):
if self.left:
self.left.PrintTree()
print(self.data)
if self.right:
self.right.PrintTree()
# Inorder traversal
res = []
if root:
res = self.inorderTraversal(root.left)
res.append(root.data)
return res
root = Node(27)
root.insert(14)
root.insert(35)
root.insert(10)
root.insert(19)
root.insert(31)
root.insert(42)
print(root.inorderTraversal(root))
Output:
Aim:
To write a Python program for preorder traverse to search element from binary tree.
Algorithm:
2. Initially all the left and right vertex are None, then declare the values using
insert() function.
class Node:
def__init__(self, data):
self.left = None
self.right = None
self.data = data
# Insert Node
if self.data:
if data<self.data:
if self.left is None:
self.left = Node(data)
else:
self.left.insert(data)
elif data>self.data:
if self.right is None:
self.right = Node(data)
else:
self.right.insert(data)
else:
self.data = data
def PrintTree(self):
if self.left:
self.left.PrintTree()
print(self.data)
if self.right:
self.right.PrintTree()
# Preorder traversal
res = []
if root:
res.append(root.data)
res = self.PreorderTraversal(root.left)
return res
root = Node(27)
root.insert(14)
root.insert(35)
root.insert(10)
root.insert(19)
root.insert(31)
root.insert(42)
print(root.PreorderTraversal(root))
Output:
Aim:
To write a Python program for postorder traverse to search element from binary tree.
Algorithm:
2. Initially all the left and right vertex are None, then declare the values using
insert() function.
class Node:
def__init__(self, data):
self.left = None
self.right = None
self.data = data
# Insert Node
if self.data:
if data<self.data:
if self.left is None:
self.left = Node(data)
else:
self.left.insert(data)
elif data>self.data:
if self.right is None:
self.right = Node(data)
else:
self.right.insert(data)
else:
self.data = data
def PrintTree(self):
if self.left:
self.left.PrintTree()
print(self.data)
if self.right:
self.right.PrintTree()
# Postorder traversal
res = []
if root:
res = self.PostorderTraversal(root.left)
res.append(root.data)
return res
root = Node(27)
root.insert(14)
root.insert(35)
root.insert(10)
root.insert(19)
root.insert(31)
root.insert(42)
print(root.PostorderTraversal(root))
Output:
Aim:
To write a Python program to insert element into binary tree and display inorder vertical
order.
Algorithm:
Program:
class Node:
self.left = None
self.right = None
self.val = key
if root is None:
if root.val == key:
return root
else:
return root
def inorder(root):
if root:
inorder(root.left)
print(root.val)
inorder(root.right)
# 50
#/
# 30 70
#/\/\
# 20 40 60 80
r = Node (50)
r = insert (r,30)
r = insert (r,20)
r = insert (r,40)
r = insert (r,70)
r = insert (r,60)
r = insert (r,80)
inorder (r)
Output:
20
30
40
50
60
70
80
EX.NO.10B IMPLEMENTATION OF BINARY SEARCH TREE - SEARCH
Aim:
Algorithm:
2. Compare the search element with the value of root node in the tree.
3. If both are matched, then display "Given node is found!!!" and terminate the
function.
4. If both are not matched, then check whether search element is smaller or larger
than that node value.
5. If search element is smaller, then continue the search process in left subtree.
6. If search element is larger, then continue the search process in right subtree.
7. Repeat the same until we find the exact element or until the search element is
compared with the leaf node.
8. If we reach to the node having the value equal to the search value then display
"Element is found" and terminate the function.
Program:
class Node:
# Assign data to the new node, set left and right children to None
self.data = data
self.left = None
self.right = None
class SearchBinaryTree:
def __init__(self):
self.root = None
self.flag = False
if (self.root == None):
else:
if (temp.data == value):
return
self.searchNode(temp.left,value)
bt = SearchBinaryTree()
bt.searchNode(bt.root, 5)
if (bt.flag):
else:
Output:
Aim:
To write a python program to find min heap.
Algorithm:
Program:
Class MinHeap:
def __init__(self, maxsize):
self.maxsize = maxsize
self.size = 0
self.Heap = [0]*(self.maxsize + 1)
self.Heap[0] = -1 * sys.maxsize
self.FRONT = 1
# Function to return the position of parent for the node currently at pos
def parent (self, pos):
return pos // 2
# Function to return the position of the left child for the node currently at pos
def leftChild (self, pos):
return 2* pos
# Function to return the position of the right child for the node currently at pos
def rightChild (self, pos):
return (2 * pos) + 1
# Function that returns true if the passed node is a leaf node
def isLeaf (self,pos):
return pos * 2 > self.size
# Function to swap two nodes of the heap
def swap (self, fpos, spos):
self.Heap[fpos], self.Heap[spos] = self.Heap[spos], self.Heap[fpos]
# Function to heapify the node at pos
def minHeapify(self, pos):
# if the node is a non-leaf node and greater than any of its child
if not self.isLeaf(pos):
if (self.Heap[pos] > self.Heap[self.leftChild(pos)] or
self.Heap[pos] > self.Heap[self.rightChild(pos)]):
# Swap with the left child and heapify the left child
if self.Heap[self.leftChild(pos)] < self.Heap[self.rightChild(pos)]:
self.swap(pos, self.leftChild(pos))
self.minHeapify(self.leftChild(pos))
# Swap with the right child and heapify the right child
else:
self.swap(pos, self.rightChild(pos))
self.minHeapify(self.rightChild(pos)
return
self.size+=1
self.Heap[self.size] = element
current=self.size
self.swap(current, self.parent(current))
current=self.parent(current)
def Print(self):
def minheap(self):
self.minHeapify(pos)
# Function to remove and return the minimum element from the heap
def remove(self):
popped = self.Heap[self.FRONT]
self.Heap[self.FRONT] = self.Heap[self.size]
self.size -= 1
self.minHeapify(self.FRONT)
return popped
# Driver Code
if __name__ == “__main__”:
minheap= MinHeap(15)
minHeap.insert(5)
minHeap.insert(3)
minHeap.insert(17)
minHeap.insert(10)
minHeap.insert(84)
minHeap.insert(19)
minHeap.insert(6)
minHeap.insert(22)
minHeap.insert(9)
minheap.minHeap()
minheap.Print()
Output:
The minHeap is
Aim:
To write a python program to find max heap.
Algorithm:
Program:
Class MaxHeap:
def __init__(self, maxsize):
self.maxsize = maxsize
self.size = 0
self.Heap = [0]*(self.maxsize + 1)
self.Heap[0] = sys.maxsize
self.FRONT = 1
# Function to return the position of parent for the node currently at pos
def parent (self, pos):
return pos // 2
# Function to return the position of the left child for the node currently at pos
def leftChild (self, pos):
return 2* pos
# Function to return the position of the right child for the node currently at pos
def rightChild (self, pos):
return (2 * pos) + 1
# Function that returns true if the passed node is a leaf node
def isLeaf (self, pos):
if pos >= (self.size // 2) and pos <= self.size:
return True
return False
# Function to swap two nodes of the heap
def swap (self, fpos, spos):
self.Heap[fpos], self.Heap[spos] = (self.Heap[spos], self.Heap[fpos])
# Function to heapify the node at pos
def maxHeapify(self, pos):
# if the node is a non-leaf node and smaller than any of its child
if not self.isLeaf(pos):
if (self.Heap[pos] < self.Heap[self.leftChild(pos)] or
self.Heap[pos] < self.Heap[self.rightChild(pos)]):
# Swap with the left child and heapify the left child
if self.Heap[self.leftChild(pos)] > self.Heap[self.rightChild(pos)]:
self.swap(pos, self.leftChild(pos))
self.maxHeapify(self.leftChild(pos))
# Swap with the right child and heapify the right child
else:
self.swap(pos, self.rightChild(pos))
self.maxHeapify(self.rightChild(pos)
return
self.size+=1
self.Heap[self.size] = element
current=self.size
self.swap(current, self.parent(current))
current=self.parent(current)
def Print(self):
# Function to remove and return the maximum element from the heap
def extractMax(self):
popped = self.Heap[self.FRONT]
self.Heap[self.FRONT] = self.Heap[self.size]
self.size -= 1
self.maxHeapify(self.FRONT)
return popped
# Driver Code
if __name__ == “__main__”:
minheap= MaxHeap(15)
maxHeap.insert(5)
maxHeap.insert(3)
maxHeap.insert(17)
maxHeap.insert(10)
maxHeap.insert(84)
maxHeap.insert(19)
maxHeap.insert(6)
maxHeap.insert(22)
maxHeap.insert(9)
minheap.Print()
Output:
The maxHeap is
Aim:
Algorithm:
Program:
class AdjNode:
def __init__(self,value):
self.vertex = value
self.next = None
class Graph:
def__init__(self,num)
self.V = num
# Add edges
node = AdjNode(d)
node.next = self.graph[s]
self.graph[s] = node
node = AdjNode(s)
node.next = self.graph[d]
self.graph[d] = node
for i in range(self.V):
temp = self.graph[i]
while temp:
temp = temp.next
print(“ \n”)
if __name__ == “ __main__”:
V=5
graph = Graph(V)
graph.add_edge(0,1)
graph.add_edge(0,2)
graph.add_edge(0,3)
graph.add_edge(1,2)
graph.print_agraph()
Output:
Vertex 4:
Ex. No. 12C DEPTH FIRST TRAVERSAL
Aim:
Algorithm:
Program:
class Graph:
# Constructor
self.graph = defaultdict(list)
self.graph[u].append(v)
visited.add(v)
print(v, end = ‘ ‘)
def DFS(self,v):
visited = set()
Self.DFSUtil(v, visited)
# Driver code
g = Graph()
g.addEdge(0,1)
g.addEdge(0,2)
g.addEdge(1,2)
g.addEdge(2,0)
g.addEdge(2,3)
g.addEdge(3,3)
g.DFS(2)
Output:
EX. NO. 12D BREADTH FIRST TRAVERSAL
Aim:
Algorithm:
Program:
graph = {
‘5’ : [‘3’,’7’],
‘7’ : [‘8’],
‘2’ : [],
‘4’ : [‘8’],
‘8’ : []
visited.append(node)
queue.append(node)
m = queue.pop(0)
print(m, end = “ “)
visited.append(neighbour)
queue.append( neighbour)
# Driver Code
Output:
5 3 7 2 4 8
EX. NO. 13A SINGLE SOURCE SHORTEST PATH ALGORITHM
Bellman Ford Algorithm
Aim:
To write a Python program for single source shortest path using Bellman Ford Algorithm.
Algorithm:
Program:
def __init__(self, vertices):
self.M = vertices # Total number of vertices in the graph
self.graph = [] # Array of edges
# Add edges
def add_edge(self, a, b,c):
self.graph.append([a, b, c])
Output:
Vertex Distance from Source
0 0
1 2
2 4
3 2
4 7
EX. NO. 13B SINGLE SOURCE SHORTEST PATH ALGORITHM
Dijiktra’s Algorithm
Aim:
To write a Python program for single source shortest path using Dijiktra’s Algorithm.
Algorithm:
Program:
# Python program for Dijiktra’s single source shortest path algorithm. The program is for
# adjacency matrix representation of the graph.
class Graph():
def __ init__self(self, vertices):
self.V = vertices
self.graph = [[0 for column in range(vertices)] for row in range(vertices)]
def printSolution(self, dist):
print(“Vertex \t Distance from Source”)
for node in range(self.V):
print(node, “\t\t”, dist[node])
# A utility function to find the vertex with minimum distance value, from the set of
# vertices not yet included in shortest path tree
def minDistance(self, dist, sptSet):
# Initialize minimum distance for next node
min = 1e7
# Search not nearest vertex not in the shortest path tree
for v in range(self.V):
if dist[v] < min and sptSet[v] == False:
min = dist[v]
min_index = v
return min_index
# Function that implements Dijiktra’s single source shortest path algorithm for a graph
# represented using adjacency matrix representation
def dijktra(self, src):
dist = [ 1e7] * self.V
dist[src] = 0
sptSet = [False] * self.V
for cout in range(self.V):
# Pick the minimum distance vertex from the set of vertices not yet processed.
# u is always equal to src in first iteration
u = self.minDistance(dist, sptSet)
# Put the minimum distance vertex in the shortest path tree
sptSet[u] = True
# Update dist value of the adjacent vertices of the picked vertex only if the
# current distance is greater than new distance and the vertex is not in the
# shortest path tree
for v in range(self.V):
if(self.graph[u][v] > 0 and sptSet[v] == False and dist[v] > dist[u] +
self.graph[u][v]);
dist[v] = dist[u] + selfgraph[u][v]
self.printSolution(dist)
# Driver program
g = Graph(9)
g.graph = [[0, 4, 0, 0, 0, 0, 0, 8, 0],
[4, 0, 8, 0, 0, 0, 0, 11, 0],
[0, 8, 0, 7, 0, 4, 0, 0, 2],
[0, 0, 7, 0, 9, 14, 0, 0, 0],
[0, 0, 0, 9, 0, 10, 0, 0, 0],
[0, 0, 4, 14, 10, 0, 2, 0, 0]
[0, 0, 0, 0, 0, 2, 0, 1, 6]
[8, 11, 0, 0, 0, 0, 1, 0, 7]
[0, 0, 2, 0, 0, 0, 6, 7, 0]
]
g.dijktra(0)
Output:
Aim:
To write a Python program to find minimum spanning tree from a given graph using
Prim’s algorithm.
Algorithm:
Program:
# A Python program for Prim’s Minimum Spanning Tree (MST) algorithm.
# The program is for adjacency matrix representation of the graph.
import sys # Library for INT_MAX
class Graph():
def __init__(self, vertices):
self.V = vertices
self.graph = [[ 0 for column in range(vertices)] for row in range(vertices)]
# A utility function to print the constructed MST stored in parent[]
def printMST(self, parent):
print(“Edge \tWeight”)
for i in range(1, self.V):
print(parent[i], “-“, I, “\t”, self.graph[i][parent[i]])
# A utility function to find the vertex with minimum distance value, from the set of
# vertices not yet included in shortest path tree
def minKey(self, key, mstSet):
# Initialize min value
min = sys.maxsize
for v in range(self.V)
if key[v] < min and mstSet[v] == False:
min = key[v]
min_index = v
return min_index
# Function to construct and print MST for a graph represented using adjacency matrix
# representation
def printMST(self):
# Key values used to pick minimum weight edge in cut
key = [sys.maxsize] * self.V
parent = [None] * self.V # Array to store constructed MST
# Make key 0 so that this vertex is picked as first vertex
key[0] = 0
mstSet = [False] * self.V
# Update dist value of the adjacent vertices of the picked vertex only if the
# current distance is greater than new distance and the vertex is not in the shortest
# path tree
for v in range(self.V):
# graph[u][v] is non zero only for adjacent vertices of m
# mstSet[v] is False for vertices not yet included in MST
# Update the key only if graph[u][v] is smaller than key[v
if self.graph[u][v] > 0 and mstSet[v] == False and key[v] > self.graph[u][v]:
key[v] = self.graph[u][v]
parent[v] = u
self.printMST(parent)
g = Graph(5)
g.graph = [ [0, 2, 0, 6, 0],
[2, 0, 3, 8, 5],
[0, 3, 0, 0, 7]
[6, 8, 0, 0, 9],
[0, 5, 7, 9, 0] ]
g.primMST()
Output:
Edge Weight
0–1 2
1–2 3
0–3 6
1–4 5
EX. NO. 14B IMPLEMENTATION OF MINIMUM SPANNING TREE
Kruskal’s algorithm
Aim:
To Write a Python program to find minimum spanning tree from a given graph using
Kruskal algorithm.
Algorithm:
1. Label each vertex
2. List the edges in non-decreasing order of weight.
3. Start with the smallest weighted and beginning growing the minimum weighted
spanning tree from this edge.
4. Add the next available edge that does not form a cycle to the construction of the
minimum weighted spanning tree. If the addition of the next least weighted edge
forms a cycle, do not use it.
5. Continue with step 4 until you have a spanning tree.
6. Stop the program.
Program:
from collections import defaultdict
class Graph:
def __init__(self,vertices):
self.V = vertices # No. of vertices
self.graph.append([u, v, w])
if parent[i] == i:
return i
return self.find(parent,parent[i])
# A function that does union of two sets of x and y (uses union by rank)
xroot = self.find(parent, x)
yroot = self.find(parent, y)
# Attach smaller rank tree under root of high rank tree (Union by Rank)
if rank[xroot]< rank[yroot]:
parent[xroot] = yroot
parent[yroot] = xroot
# If ranks are same, then make one as root and increment its rank by one
else:
parent[yroot] = xroot
rank[xroot] += 1
def KruskalMST(self):
i=0;
e=0
# Step 1: Sort all the edges in non-decreasing order of their weight. If we are not
parent = []
rank = []
parent.append(node)
rank.append(0)
# Step 2: Pick the smallest edge and increment the index for next iteration
u, v, w = self.graph[i]
i = i+1
x = self.find(parent, u)
y = self.find(parent, v)
# If including this edge doesn’t cause cycle, include it in result and increment
minimumCost = 0
minimumCost += weight
# Driver code
g = Graph(4)
g.addEdge(0, 1, 10)
g.addEdge(0, 2, 6)
g.addEdge(0, 3, 5)
g.addEdge(1, 3, 15)
g.addEdge(2, 3, 4)
# Function call
g.KruskalMST()
Output:
2 -- 3 == 4
0 -- 3 == 5
0 -- 1 == 10