0% found this document useful (0 votes)
4 views

Lab#10 Binary Search Tree-merged

This document outlines the implementation of a Binary Search Tree (BST) including algorithms for insertion, searching, and deletion of nodes. It also includes lab tasks for creating a BST from a list of elements, merging two BSTs, and inserting a new element. Additionally, it provides a brief overview of graph traversal techniques such as Breadth First Search (BFS).

Uploaded by

hamza zahid
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
4 views

Lab#10 Binary Search Tree-merged

This document outlines the implementation of a Binary Search Tree (BST) including algorithms for insertion, searching, and deletion of nodes. It also includes lab tasks for creating a BST from a list of elements, merging two BSTs, and inserting a new element. Additionally, it provides a brief overview of graph traversal techniques such as Breadth First Search (BFS).

Uploaded by

hamza zahid
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 22

Lab#11 Implementation of Binary Search Tree SSUET/QR/114

LAB # 11

Implementation of Binary Search Tree

Objective: Algorithm to implement binary search tree.

A binary search tree is a tree where each node contains a value, and for each node, the
left sub-tree only contains values less than the value of the node and the right sub-tree
only contains greater values. This allows finding the node for any value in O (logN)
average time.

Algorithm for insertion

InserBST (Root, item)


1. Set ptr=Root, pptr=NULL
2. New=createnode()
3. Setdata(new, item)
4. Setleftchild(new, NULL)
5. setRightchild(new, NULL)
6. Repeat while ptr =! NULL
Set pptr=ptr
if getdata(ptr) > Item then
ptr =getleftchild(ptr)
else
7. Set ptr=getrightchild(ptr)
[End of loop]
8. if getdata(pptr) > item then
setleftchild(pptr,new)
9. else
setrightchild(pptr,new)

Algorithm for searching

SearchBST (Root, Item, loc, locp)


1. Set ptr = Root, pptr=loc = NULL
2. Repeat while ptr =! NULL
3. If getdata(ptr) = item then
Set loc=ptr, locp=pptr and exit loop
4. Else if getdata(ptr) > item then
Set Pptr=ptr
ptr =getleftchild(ptr)
5. Else
Set Pptr=ptr
ptr=getrightchild(ptr)
[End of loop]
6. Return loc=ptr, locp=pptr

SWE-203L Data Structures & Algorithms


Lab#11 Implementation of Binary Search Tree SSUET/QR/114

This procedure deletes the node N at location LOC, where N does not have two
children the pointer PAR gives the location of the parent of N, or else PAR=NULL
indicates that N is the ROOT node. The pointer CHILD gives the location of the only
child of N, or else CHILD=NULL indicates N has no children.

Algorithm for deletion

DeleteChild (Root, Loc, Locp, Item,)


Item=getdata(loc)
[Deleting leaf node]
If getleftchild(loc)=getrightchild(loc)=NULL than
If loc=root and locp=NULL then
Root=NULL
Else If getleftchild(locp) =loc, then:
setleftchild(locp,NULL)

else
setrightchild(locp,NULL)
[Deleting node with one child]
Else If getleftchild(loc) != NULL and getrightchild(loc)=NULL, then:

If getleftchild(locp) =loc, then:

setleftchild(locp,getleftchild(loc))
else
setrightchild(locp, getleftchild(loc))
Else If getleftchild(loc) = NULL and getrightchild(loc) !=NULL, then:

If getleftchild(locp) =loc, then:


setleftchild(locp,getrightchild(loc))
else
setrightchild(locp, getrightchild(loc))

(End of if structure)

Return updated Root and item

This procedure will delete the node N at location LOC where N has two children. The
pointer PAR gives the location of the parent N or else PAR=NULL indicates that N is
the ROOT node. The pointer SUC gives the location of the inorder successor of N,
and PARSUC gives the location of the parent the inorder successor.

DeleteMiddleNode (Root, Loc, locp, item)


Item=getdata(loc)
[Find SUC and PARSUC]
Set PTR:=getrightchild(loc) and SAVE:=LOC
Repeat while getleftchild(ptr) != NULL:
Set SAVE: =PTR and PTR: =getleftchild(ptr)
(End of Loop)

SWE-203L Data Structures & Algorithms


Lab#11 Implementation of Binary Search Tree SSUET/QR/114

Set SUC:=PTR and PARSUC:=SAVE


[Delete in order successor, using procedure deletechild()]
Call DeleteChild(Root, suc, parsuc, item)

[Replace node pointed by loc by its inorder successor]

If locp != NULL then:


If LOC=getleftchild(locp), then
Set setleftchild(locp,SUC)

Else:
Set setrightchild(locp,SUC)
(End of if structure)
Else:
Set ROOT: =SUC
(End of if structure)
Set setleftchild(suc, getleftchild(loc)) and Setrightchild(suc, getrightchild(loc))
Return Root and item

Lab Task

1. Write a program that takes an item input to search if there is a item present, deletes
it otherwise insert it in a tree.

2. Write a program to create binary search tree of the following list of elements;
- 45, 15, 79, 90, 10, 55, 12, 20, 50

Home Task

1. Write a function called MergeBST that give a combine Binary search tree of two
different binary search trees according to rules of binary tree then print all nodes.

2. Write a program to insert new element ‘60’ in the Binary tree created in above
ques.2.

SWE-203L Data Structures & Algorithms


Lab # 10

Q1. Write a program that takes an item input to search if there is a item present, deletes it
otherwise insert it in a tree.
Code:
import java.util.*;

class Node {
String data;
Node left, right;

Node(String data) {
this.data = data;
this.left = this.right = null;
}}
class BinaryTree {
Node root;

Node insert(Node root, String key) {


if (root == null) return new Node(key);
if (key.compareTo(root.data) < 0) root.left = insert(root.left, key);
else if (key.compareTo(root.data) > 0) root.right = insert(root.right, key);
return root;
}

Node delete(Node root, String key) {


if (root == null) return null;
if (key.compareTo(root.data) < 0) root.left = delete(root.left, key);
else if (key.compareTo(root.data) > 0) root.right = delete(root.right, key);
else {
if (root.left == null) return root.right;
if (root.right == null) return root.left;
Node minNode = findMin(root.right);
root.data = minNode.data;
root.right = delete(root.right, minNode.data);
}
return root;
}
Node findMin(Node root) {
while (root.left != null) root = root.left;
return root;
}

boolean search(Node root, String key) {


if (root == null) return false;
if (key.equals(root.data)) return true;
return key.compareTo(root.data) < 0 ? search(root.left, key) : search(root.right, key);
}

void inorder(Node root) {


if (root != null) {
inorder(root.left);
System.out.print(root.data + " ");
inorder(root.right);
}}}
public class TreeItemManager {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
BinaryTree tree = new BinaryTree();

while (true) {
System.out.println("Enter an item (or 'exit' to quit):");
String item = scanner.nextLine();
if (item.equals("exit")) break;

if (tree.search(tree.root, item)) {
System.out.println("Item found, deleting...");
tree.root = tree.delete(tree.root, item);
} else {
System.out.println("Item not found, inserting...");
tree.root = tree.insert(tree.root, item);
}
System.out.println("Current tree (in-order):");
tree.inorder(tree.root);
System.out.println();
}}}
Output:
Item not found, inserting...
Current tree (in-order):
apple
Item not found, inserting...
Current tree (in-order):
apple banana
Item found, deleting...
Current tree (in-order):
banana
Q2. Write a program to create binary search tree of the following list of elements;
- 45, 15, 79, 90, 10, 55, 12, 20, 5
Code:
import java.util.*;

class Node {
int data;
Node left, right;

Node(int data) {
this.data = data;
this.left = this.right = null;
}}
class BinaryTree {
Node root;

Node insert(Node root, int key) {


if (root == null) return new Node(key);
if (key < root.data) root.left = insert(root.left, key);
else if (key > root.data) root.right = insert(root.right, key);
return root;
}

void inorder(Node root) {


if (root != null) {
inorder(root.left);
System.out.print(root.data + " ");
inorder(root.right);
}}}
public class TreeItemManager {
public static void main(String[] args) {
BinaryTree tree = new BinaryTree();
int[] elements = {45, 15, 79, 90, 10, 55, 12, 20, 5};

for (int element : elements) {


tree.root = tree.insert(tree.root, element);
}
System.out.println("In-order traversal of the binary search tree:");
tree.inorder(tree.root);
}}
Output:
In-order traversal of the binary search tree:
5 10 12 15 20 45 55 79 90
Q3. Write a function called MergeBST that give a combine Binary search tree of two
different binary search trees according to rules of binary tree then print all nodes.
Code:
import java.util.*;

class Node {
int data;
Node left, right;

Node(int data) {
this.data = data;
this.left = this.right = null;
}
}

class BinaryTree {
Node root;

Node insert(Node root, int key) {


if (root == null) return new Node(key);
if (key < root.data) root.left = insert(root.left, key);
else if (key > root.data) root.right = insert(root.right, key);
return root;
}

void inorder(Node root) {


if (root != null) {
inorder(root.left);
System.out.print(root.data + " ");
inorder(root.right);
}}
void mergeTrees(Node root1, Node root2) {
List<Integer> elements = new ArrayList<>();
storeInOrder(root1, elements);
storeInOrder(root2, elements);
Collections.sort(elements);

root = null;
for (int element : elements) {
root = insert(root, element);
}}
void storeInOrder(Node root, List<Integer> elements) {
if (root != null) {
storeInOrder(root.left, elements);
elements.add(root.data);
storeInOrder(root.right, elements);
}}}
public class TreeItemManager {
public static void main(String[] args) {
BinaryTree tree1 = new BinaryTree();
BinaryTree tree2 = new BinaryTree();

int[] elements1 = {45, 15, 79, 10, 55};


int[] elements2 = {90, 12, 20, 5};

for (int element : elements1) {


tree1.root = tree1.insert(tree1.root, element);
}

for (int element : elements2) {


tree2.root = tree2.insert(tree2.root, element);
}

BinaryTree mergedTree = new BinaryTree();


mergedTree.mergeTrees(tree1.root, tree2.root);

System.out.println("In-order traversal of the merged binary search tree:");


mergedTree.inorder(mergedTree.root);
}}
Output:
In-order traversal of the merged binary search tree:
5 10 12 15 20 45 55 79 90

Q4. Write a program to insert new element ‘60’ in the Binary tree created in above ques.2.
Code:
import java.util.*;

class Node {
int data;
Node left, right;

Node(int data) {
this.data = data;
this.left = this.right = null;
}}
class BinaryTree {
Node root;
Node insert(Node root, int key) {
if (root == null) return new Node(key);
if (key < root.data) root.left = insert(root.left, key);
else if (key > root.data) root.right = insert(root.right, key);
return root;
}
void inorder(Node root) {
if (root != null) {
inorder(root.left);
System.out.print(root.data + " ");
inorder(root.right);
}}
void mergeTrees(Node root1, Node root2) {
List<Integer> elements = new ArrayList<>();
storeInOrder(root1, elements);
storeInOrder(root2, elements);
Collections.sort(elements);

root = null;
for (int element : elements) {
root = insert(root, element);
}}
void storeInOrder(Node root, List<Integer> elements) {
if (root != null) {
storeInOrder(root.left, elements);
elements.add(root.data);
storeInOrder(root.right, elements);
}}}
public class TreeItemManager {
public static void main(String[] args) {
BinaryTree tree = new BinaryTree();
int[] elements = {45, 15, 79, 90, 10, 55, 12, 20, 5};

for (int element : elements) {


tree.root = tree.insert(tree.root, element);
}

System.out.println("Binary search tree before inserting 60:");


tree.inorder(tree.root);

tree.root = tree.insert(tree.root, 60);


System.out.println("\nBinary search tree after inserting 60:");
tree.inorder(tree.root);
}}
Output:
Binary search tree before inserting 60:
5 10 12 15 20 45 55 79 90
Binary search tree after inserting 60:
5 10 12 15 20 45 55 60 79 90
Lab#12 Graph and Graph Traversals SSUET/QR/114

LAB # 12

Graph and Graph Traversals

Objective: Implementing graph using BFS and DFS.

The graph is one non-linear data structure which consists of some nodes and their
connected edges. The edges may be directed or undirected.

Breadth First Search (BFS)

The Breadth First Search (BFS) traversal is an algorithm, which is used to visit all of
the nodes of a given graph. In this traversal algorithm one node is selected and then
all of the adjacent nodes are visited one by one. After completing all of the adjacent
vertices, it moves further to check another vertices and checks its adjacent vertices
again.

Algorithm for BFS

o Step 1: SET STATUS = 1 (ready state)


for each node in G
o Step 2: Enqueue the starting node A
and set its STATUS = 2
(waiting state)
o Step 3: Repeat Steps 4 and 5 until
QUEUE is empty
o Step 4: Dequeue a node N. Process it
and set its STATUS = 3
(processed state).
o Step 5: Enqueue all the neighbours of
N that are in the ready state
(whose STATUS = 1) and set
their STATUS = 2
(waiting state)
[END OF LOOP]
o STEP 6: exit

Sample Program#1
// Java program to print BFS traversal from a given source vertex.
// BFS(int s) traverses vertices reachable from s.
import java.io.*;
import java.util.*;

// This class represents a directed graph using adjacency list representation


class Graph {
private int V; // No. of vertices
private LinkedList<Integer> adj[]; //Adjacency Lists
// Constructor

SWE-203L Data Structures & Algorithms


Lab#12 Graph and Graph Traversals SSUET/QR/114

Graph(int v) {
V = v;
adj = new LinkedList[v];
for (int i=0; i<v; ++i)
adj[i] = new LinkedList();
}
// Function to add an edge into the graph
void addEdge(int v,int w) {
adj[v].add(w);
}
// prints BFS traversal from a given source s
void BFS(int s) {
// Mark all the vertices as not visited(By default
// set as false)
boolean visited[] = new boolean[V];

// Create a queue for BFS


LinkedList<Integer> queue = new LinkedList<Integer>();

// Mark the current node as visited and enqueue it


visited[s]=true;
queue.add(s);

while (queue.size() != 0) {
// Dequeue a vertex from queue and print it
s = queue.poll();
System.out.print(s+" ");

// Get all adjacent vertices of the dequeued vertex s


// If a adjacent has not been visited, then mark it
// visited and enqueue it
Iterator<Integer> i = adj[s].listIterator();
while (i.hasNext()) {
int n = i.next();
if (!visited[n]) {
visited[n] = true;
queue.add(n);
}
}}}

// Driver method to
public static void main(String args[]) {
Graph g = new Graph(4);

g.addEdge(0, 1);
g.addEdge(0, 2);
g.addEdge(1, 2);
g.addEdge(2, 0);
g.addEdge(2, 3);
g.addEdge(3, 3);

SWE-203L Data Structures & Algorithms


Lab#12 Graph and Graph Traversals SSUET/QR/114

System.out.println("Following is Breadth First Traversal "+


"(starting from vertex 2)");
g.BFS(2);
}
}

Depth First Search (DFS)

The Depth First Search (DFS) is a graph traversal algorithm. In this algorithm one
starting vertex is given, and when an adjacent vertex is found, it moves to that
adjacent vertex first and try to traverse in the same manner.

Algorithm for DFS

o Step 1: SET STATUS = 1(Ready state) for each node in G


o Step 2: Push the starting node A on the stack and set its STATUS =2(waiting state)
o Step 3: Repeat Steps 4 and 5 until STACK is empty
o Step 4: Pop the top node N. Process it and set its STATUS=3 (processed state)
o Step 5: Push on the stackall the neighbours of N that are in the ready state(whose
STATUS=1) and set their
STATUS=2 (waiting state)
[END OF LOOP]
o Step 6: EXIT

Sample program #2
// Java program to print DFS traversal from a given graph
import java.io.*;
import java.util.*;

// This class represents a directed graph using adjacency list representation


class Graph {
private int V; // No. of vertices

// Array of lists for


// Adjacency List Representation
private LinkedList<Integer> adj[];

// Constructor
@SuppressWarnings("unchecked") Graph(int v) {
V = v;
adj = new LinkedList[v];
for (int i = 0; i < v; ++i)
adj[i] = new LinkedList();
}
// Function to add an edge into the graph
void addEdge(int v, int w) {
adj[v].add(w); // Add w to v's list.
}
// A function used by DFS

SWE-203L Data Structures & Algorithms


Lab#12 Graph and Graph Traversals SSUET/QR/114

void DFSUtil(int v, boolean visited[]) {


// Mark the current node as visited and print it
visited[v] = true;
System.out.print(v + " ");

// Recur for all the vertices adjacent to this


// vertex
Iterator<Integer> i = adj[v].listIterator();
while (i.hasNext()) {
int n = i.next();
if (!visited[n])
DFSUtil(n, visited);
}}

// The function to do DFS traversal.


// It uses recursive
// DFSUtil()
void DFS(int v) {
// Mark all the vertices as
// not visited(set as
// false by default in java)
boolean visited[] = new boolean[V];

// Call the recursive helper


// function to print DFS
// traversal
DFSUtil(v, visited);
}
// Driver's Code
public static void main(String args[]) {
Graph g = new Graph(4);
g.addEdge(0, 1);
g.addEdge(0, 2);
g.addEdge(1, 2);
g.addEdge(2, 0);
g.addEdge(2, 3);
g.addEdge(3, 3);

System.out.println(
"Following is Depth First Traversal "
+ "(starting from vertex 2)");

// Function call
g.DFS(2);
}
}

SWE-203L Data Structures & Algorithms


Lab#12 Graph and Graph Traversals SSUET/QR/114

Lab Task

1. Implement BFS and DFS on the given graph.

2. Follow the below instructions to implement BFS traversal.

⚫ Declare a queue and insert the starting vertex.


⚫ Initialize a visited array and mark the starting vertex as visited.

Follow the below process till the queue becomes empty:


⚫ Remove the first vertex of the queue.
⚫ Mark that vertex as visited.
⚫ Insert all the unvisited neighbours of the vertex into the queue.

Home Task

1. Implement BFS and DFS on the below given graph.

2. Write a JAVA program that creates a recursive function that takes the index of the
node and a visited array. Mark the current node as visited and print the node and

SWE-203L Data Structures & Algorithms


Lab#12 Graph and Graph Traversals SSUET/QR/114

traverse all the adjacent and unmarked nodes and call the recursive function with the
index of the adjacent node.

SWE-203L Data Structures & Algorithms


Lab # 11
Q1. Implement BFS and DFS on the given graph.
Code:
import java.util.*;

public class GraphTraversal {


private int vertices; // Number of vertices
private LinkedList<Integer>[] adj; // Adjacency list

public GraphTraversal(int vertices) {


this.vertices = vertices;
adj = new LinkedList[vertices];
for (int i = 0; i < vertices; i++) {
adj[i] = new LinkedList<>();
}} public void addEdge(int v, int w) {
adj[v].add(w);
adj[w].add(v); // Since the graph is undirected
}

public void bfs(int start) {


boolean[] visited = new boolean[vertices];
Queue<Integer> queue = new LinkedList<>();
visited[start] = true;
queue.add(start);

while (!queue.isEmpty()) {
int node = queue.poll();
System.out.print(node + " ");

for (int neighbor : adj[node]) {


if (!visited[neighbor]) {
visited[neighbor] = true;
queue.add(neighbor);}}}
System.out.println();}
public void dfsUtil(int node, boolean[] visited) {
visited[node] = true;
System.out.print(node + " ");
for (int neighbor : adj[node]) {
if (!visited[neighbor]) {
dfsUtil(neighbor, visited);
}}}
public void dfs(int start) {
boolean[] visited = new boolean[vertices];
dfsUtil(start, visited);
System.out.println();
}

public static void main(String[] args) {


GraphTraversal graph = new GraphTraversal(5);
graph.addEdge(0, 1);
graph.addEdge(0, 3);
graph.addEdge(0, 2);
graph.addEdge(2, 4);

System.out.println("BFS Traversal:");
graph.bfs(0);

System.out.println("DFS Traversal:");
graph.dfs(0);
}}
Output:
BFS Traversal:
01324
DFS Traversal:
01324

Q2 Follow the below instructions to implement BFS traversal.

• Declare a queue and insert the starting vertex.


• Initialize a visited array and mark the starting vertex as visited.

Follow the below process till the queue becomes empty:

• Remove the first vertex of the queue.


• Mark that vertex as visited.
• Insert all the unvisited neighbours of the vertex into the queue.

Code:
import java.util.*;

public class GraphTraversal {


private int vertices;
private LinkedList<Integer>[] adj;

public GraphTraversal(int vertices) {


this.vertices = vertices;
adj = new LinkedList[vertices];
for (int i = 0; i < vertices; i++) {
adj[i] = new LinkedList<>();
} }
public void addEdge(int v, int w) {
adj[v].add(w);
adj[w].add(v);
}
public void bfs(int start) {
boolean[] visited = new boolean[vertices];
Queue<Integer> queue = new LinkedList<>();
queue.add(start);
visited[start] = true;

while (!queue.isEmpty()) {
int node = queue.poll();
System.out.print(node + " ");
for (int neighbor : adj[node]) {
if (!visited[neighbor]) {
queue.add(neighbor);
visited[neighbor] = true;
}}}
System.out.println();}
public static void main(String[] args) {
GraphTraversal graph = new GraphTraversal(5);
graph.addEdge(0, 1);
graph.addEdge(0, 3);
graph.addEdge(0, 2);
graph.addEdge(2, 4);
graph.bfs(0);
}}
Output:
01324

Q3. Implement BFS and DFS on the below given graph.


Code:
import java.util.*;

public class GraphTraversal {


private int vertices;
private LinkedList<Integer>[] adj;

public GraphTraversal(int vertices) {


this.vertices = vertices;
adj = new LinkedList[vertices];
for (int i = 0; i < vertices; i++) {
adj[i] = new LinkedList<>();
}}
public void addEdge(int v, int w) {
adj[v].add(w);
}
public void bfs(int start) {
boolean[] visited = new boolean[vertices];
Queue<Integer> queue = new LinkedList<>();
queue.add(start);
visited[start] = true;

while (!queue.isEmpty()) {
int node = queue.poll();
System.out.print(node + " ");
for (int neighbor : adj[node]) {
if (!visited[neighbor]) {
queue.add(neighbor);
visited[neighbor] = true;
}}}
System.out.println();
}
public void dfsUtil(int node, boolean[] visited) {
visited[node] = true;
System.out.print(node + " ");
for (int neighbor : adj[node]) {
if (!visited[neighbor]) {
dfsUtil(neighbor, visited);
}}}
public void dfs(int start) {
boolean[] visited = new boolean[vertices];
dfsUtil(start, visited);
System.out.println();
}
public static void main(String[] args) {
GraphTraversal graph = new GraphTraversal(8); // Number of nodes: 0 to 7
graph.addEdge(0, 1); // 40 -> 20
graph.addEdge(0, 2); // 40 -> 10
graph.addEdge(1, 2); // 20 -> 10
graph.addEdge(1, 3); // 20 -> 30
graph.addEdge(1, 5); // 20 -> 60
graph.addEdge(1, 4); // 20 -> 50
graph.addEdge(2, 3); // 10 -> 30
graph.addEdge(3, 5); // 30 -> 60
graph.addEdge(5, 6); // 60 -> 70
graph.addEdge(4, 6); // 50 -> 70

System.out.println("BFS Traversal:");
graph.bfs(0); // Start from 40 (node 0)

System.out.println("DFS Traversal:");
graph.dfs(0); // Start from 40 (node 0)
}}
Output:
BFS Traversal:
0123546

DFS Traversal:
0123564

Q2. Write a JAVA program that creates a recursive function that takes the index of the
node and a visited array. Mark the current node as visited and print the node and traverse
all the adjacent and unmarked nodes and call the recursive function with the index of the
adjacent node.
Code:
import java.util.*;

public class GraphTraversal {


private int vertices;
private LinkedList<Integer>[] adj;

public GraphTraversal(int vertices) {


this.vertices = vertices;
adj = new LinkedList[vertices];
for (int i = 0; i < vertices; i++) {
adj[i] = new LinkedList<>();
}}
public void addEdge(int v, int w) {
adj[v].add(w);
}
public void dfsUtil(int node, boolean[] visited) {
visited[node] = true;
System.out.print(node + " ");
for (int neighbor : adj[node]) {
if (!visited[neighbor]) {
dfsUtil(neighbor, visited);
}}}
public static void main(String[] args) {
GraphTraversal graph = new GraphTraversal(8); // Number of nodes: 0 to 7
graph.addEdge(0, 1); // 40 -> 20
graph.addEdge(0, 2); // 40 -> 10
graph.addEdge(1, 2); // 20 -> 10
graph.addEdge(1, 3); // 20 -> 30
graph.addEdge(1, 5); // 20 -> 60
graph.addEdge(1, 4); // 20 -> 50
graph.addEdge(2, 3); // 10 -> 30
graph.addEdge(3, 5); // 30 -> 60
graph.addEdge(5, 6); // 60 -> 70
graph.addEdge(4, 6); // 50 -> 70

boolean[] visited = new boolean[graph.vertices];


System.out.println("DFS Traversal:");
graph.dfsUtil(0, visited); // Start from node 0 (40)
}
}
Output:

You might also like