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

data_and_file_structure_implementation_and_theory

The document contains implementations of various data structures in C, including a stack, queue, linked list, and binary search tree. Each section provides the necessary functions for creating, manipulating, and displaying the data structures. The implementations include basic operations such as insertion, deletion, traversal, and searching.
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
21 views

data_and_file_structure_implementation_and_theory

The document contains implementations of various data structures in C, including a stack, queue, linked list, and binary search tree. Each section provides the necessary functions for creating, manipulating, and displaying the data structures. The implementations include basic operations such as insertion, deletion, traversal, and searching.
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 34

Question 1.

// C program for array implementation of stack

#include <limits.h>

#include <stdio.h>

#include <stdlib.h>

// A structure to represent a stack

struct Stack {

int top;

unsigned capacity;

int* array;

};

// function to create a stack of given capacity. It initializes size of

// stack as 0

struct Stack* createStack(unsigned capacity)

struct Stack* stack = (struct Stack*)malloc(sizeof(struct Stack));

stack->capacity = capacity;

stack->top = -1;

stack->array = (int*)malloc(stack->capacity * sizeof(int));

return stack;

// Stack is full when top is equal to the last index

int isFull(struct Stack* stack)

return stack->top == stack->capacity - 1;


}

// Stack is empty when top is equal to -1

int isEmpty(struct Stack* stack)

return stack->top == -1;

// Function to add an item to stack. It increases top by 1

void push(struct Stack* stack, int item)

if (isFull(stack))

return;

stack->array[++stack->top] = item;

printf("%d pushed to stack\n", item);

// Function to remove an item from stack. It decreases top by 1

int pop(struct Stack* stack)

if (isEmpty(stack))

return INT_MIN;

return stack->array[stack->top--];

// Function to return the top from stack without removing it

int peek(struct Stack* stack)


{

if (isEmpty(stack))

return INT_MIN;

return stack->array[stack->top];

// Driver program to test above functions

int main()

struct Stack* stack = createStack(100);

push(stack, 10);

push(stack, 20);

push(stack, 30);

printf("%d popped from stack\n", pop(stack));

return 0;

Question2. Implementation of queue using array

#include <stdio.h>

#include <stdlib.h>

struct Queue {

int front, rear, capacity;

int* queue;

};
// Function to initialize the queue

struct Queue* createQueue(int capacity) {

struct Queue* q = (struct Queue*)malloc(sizeof(struct Queue));

q->capacity = capacity;

q->front = 0;

q->rear = -1;

q->queue = (int*)malloc(q->capacity * sizeof(int));

return q;

// Function to insert an element at the rear of the queue

void enqueue(struct Queue* q, int data) {

// Check if the queue is full

if (q->rear == q->capacity - 1) {

printf("Queue is full\n");

return;

// Insert element at the rear

q->queue[++q->rear] = data;

// Function to delete an element from the front of the queue

void dequeue(struct Queue* q) {

// If the queue is empty

if (q->front > q->rear) {


printf("Queue is empty\n");

return;

// Shift all elements from index 1 till rear to the left by one

for (int i = 0; i < q->rear; i++) {

q->queue[i] = q->queue[i + 1];

// Decrement rear

q->rear--;

// Function to print queue elements

void display(struct Queue* q) {

if (q->front > q->rear) {

printf("Queue is Empty\n");

return;

// Traverse front to rear and print elements

for (int i = q->front; i <= q->rear; i++) {

printf("%d <-- ", q->queue[i]);

printf("\n");

}
// Function to print the front of the queue

void front(struct Queue* q) {

if (q->rear == -1) {

printf("Queue is Empty\n");

return;

printf("Front Element is: %d\n", q->queue[q->front]);

// Driver code

int main() {

// Create a queue of capacity 4

struct Queue* q = createQueue(4);

// Print queue elements

display(q);

// Insert elements in the queue

enqueue(q, 20);

enqueue(q, 30);

enqueue(q, 40);

enqueue(q, 50);

// Print queue elements

display(q);

// Insert element in the queue


enqueue(q, 60);

// Print queue elements

display(q);

// Dequeue elements

dequeue(q);

dequeue(q);

printf("After two node deletions\n");

// Print queue elements

display(q);

printf("After one insertion\n");

enqueue(q, 60);

// Print queue elements

display(q);

// Print front of the queue

front(q);

// Free the allocated memory

free(q->queue);

free(q);
return 0;

Question 3. Implementation of Linked List with all operations.

#include <stdio.h>

#include <stdlib.h>

#define MAX_SIZE 100 // Maximum number of nodes in the linked list

// Structure to represent a node

typedef struct {

int data;

int next; // Index of the next node, -1 means no next node

} Node;

// Array to store all nodes

Node list[MAX_SIZE];

// To track free nodes

int freeList = 0;

// Initialize the linked list

void initList() {

for (int i = 0; i < MAX_SIZE - 1; i++) {

list[i].next = i + 1;

list[MAX_SIZE - 1].next = -1; // End of the list

}
// Allocate a new node and return its index

int allocateNode() {

if (freeList == -1) {

printf("Error: No space left to allocate a new node!\n");

return -1; // No space left

int allocatedIndex = freeList; // Take the first free node

freeList = list[allocatedIndex].next; // Update freeList to point to the next free node

return allocatedIndex;

// Free a node by adding it back to the free list

void freeNode(int index) {

list[index].next = freeList;

freeList = index;

// Insert data at the beginning

void insertAtBegin(int data) {

int newNodeIndex = allocateNode();

if (newNodeIndex == -1) return;

list[newNodeIndex].data = data;

list[newNodeIndex].next = list[0].next; // Point new node to the current head

list[0].next = newNodeIndex; // Update head to the new node


}

// Insert data at the end

void insertAtEnd(int data) {

int newNodeIndex = allocateNode();

if (newNodeIndex == -1) return;

list[newNodeIndex].data = data;

list[newNodeIndex].next = -1; // New node will be the last node

// Traverse to find the last node

int current = list[0].next;

if (current == -1) {

list[0].next = newNodeIndex; // If the list is empty, new node becomes the head

} else {

while (list[current].next != -1) {

current = list[current].next;

list[current].next = newNodeIndex; // Update the last node's next pointer

// Insert data after a specific node

void insertAfter(int prevData, int data) {

int current = list[0].next;

while (current != -1 && list[current].data != prevData) {

current = list[current].next;
}

if (current == -1) {

printf("Error: Node with data %d not found.\n", prevData);

return;

int newNodeIndex = allocateNode();

if (newNodeIndex == -1) return;

list[newNodeIndex].data = data;

list[newNodeIndex].next = list[current].next;

list[current].next = newNodeIndex;

// Delete a node by value

void deleteNode(int data) {

int current = list[0].next;

int prev = -1;

// Find the node with the given data

while (current != -1 && list[current].data != data) {

prev = current;

current = list[current].next;

if (current == -1) {
printf("Error: Node with data %d not found.\n", data);

return;

if (prev == -1) {

// Deleting the first node (head)

list[0].next = list[current].next;

} else {

// Delete non-head node

list[prev].next = list[current].next;

freeNode(current); // Return the node to the free list

// Search for a node by value

int searchNode(int data) {

int current = list[0].next;

while (current != -1) {

if (list[current].data == data) {

return current; // Return the index of the node

current = list[current].next;

return -1; // Node not found

}
// Traverse and print the linked list

void printList() {

int current = list[0].next;

if (current == -1) {

printf("List is empty.\n");

return;

while (current != -1) {

printf("%d -> ", list[current].data);

current = list[current].next;

printf("NULL\n");

int main() {

initList(); // Initialize the list

// Insert elements at the end

insertAtEnd(10);

insertAtEnd(20);

insertAtEnd(30);

insertAtEnd(40);

// Insert at the beginning

insertAtBegin(5);
// Insert after a specific node

insertAfter(20, 25);

// Print the list

printf("Linked List: ");

printList();

// Search for a node

int search = searchNode(25);

if (search != -1) {

printf("Node with data 25 found at index %d.\n", search);

} else {

printf("Node with data 25 not found.\n");

// Delete a node

printf("Deleting node with data 20...\n");

deleteNode(20);

// Print the list after deletion

printf("Linked List after deletion: ");

printList();

return 0;

}
Question 4. Implementation of tree in c with all operations

#include <stdio.h>

#include <stdlib.h>

// Define the structure for a node

typedef struct Node {

int data;

struct Node* left;

struct Node* right;

} Node;

// Function to create a new node

Node* createNode(int data) {

Node* newNode = (Node*)malloc(sizeof(Node));

if (!newNode) {

printf("Memory allocation error!\n");

return NULL;

newNode->data = data;

newNode->left = newNode->right = NULL;

return newNode;

// Function to insert a node in the binary search tree

Node* insert(Node* root, int data) {

// If the tree is empty, create a new node and return it

if (root == NULL) {
return createNode(data);

// Otherwise, recur down the tree

if (data < root->data) {

root->left = insert(root->left, data); // Insert in the left subtree

} else if (data > root->data) {

root->right = insert(root->right, data); // Insert in the right subtree

// Return the unchanged root pointer

return root;

// Function to search for a node with a given value

Node* search(Node* root, int data) {

if (root == NULL || root->data == data) {

return root;

// Recur down the tree

if (data < root->data) {

return search(root->left, data); // Search in the left subtree

return search(root->right, data); // Search in the right subtree

}
// Function to find the minimum value node in a tree

Node* minValueNode(Node* node) {

Node* current = node;

// Loop down to find the leftmost leaf (smallest value)

while (current && current->left != NULL) {

current = current->left;

return current;

// Function to delete a node from the binary search tree

Node* deleteNode(Node* root, int data) {

// Base case: If the tree is empty

if (root == NULL) {

return root;

// Recur down the tree

if (data < root->data) {

root->left = deleteNode(root->left, data); // Delete from the left subtree

} else if (data > root->data) {

root->right = deleteNode(root->right, data); // Delete from the right subtree

} else {

// Node with only one child or no child

if (root->left == NULL) {
Node* temp = root->right;

free(root);

return temp;

} else if (root->right == NULL) {

Node* temp = root->left;

free(root);

return temp;

// Node with two children: Get the inorder successor (smallest in the right subtree)

Node* temp = minValueNode(root->right);

// Copy the inorder successor's content to this node

root->data = temp->data;

// Delete the inorder successor

root->right = deleteNode(root->right, temp->data);

return root;

// Function to perform inorder traversal (Left, Root, Right)

void inorder(Node* root) {

if (root != NULL) {

inorder(root->left); // Visit the left subtree

printf("%d ", root->data); // Print the node data


inorder(root->right); // Visit the right subtree

// Function to perform preorder traversal (Root, Left, Right)

void preorder(Node* root) {

if (root != NULL) {

printf("%d ", root->data); // Print the node data

preorder(root->left); // Visit the left subtree

preorder(root->right); // Visit the right subtree

// Function to perform postorder traversal (Left, Right, Root)

void postorder(Node* root) {

if (root != NULL) {

postorder(root->left); // Visit the left subtree

postorder(root->right); // Visit the right subtree

printf("%d ", root->data); // Print the node data

// Function to find the height of the binary tree

int height(Node* root) {

if (root == NULL) {

return 0; // If the tree is empty, height is 0

}
int leftHeight = height(root->left); // Get the height of the left subtree

int rightHeight = height(root->right); // Get the height of the right subtree

// Return the maximum height between left and right subtree + 1 for the current node

return (leftHeight > rightHeight ? leftHeight : rightHeight) + 1;

// Function to find the size (number of nodes) of the tree

int size(Node* root) {

if (root == NULL) {

return 0; // If the tree is empty, size is 0

// Return 1 (current node) + size of the left subtree + size of the right subtree

return 1 + size(root->left) + size(root->right);

int main() {

Node* root = NULL;

// Inserting nodes into the binary search tree

root = insert(root, 50);

root = insert(root, 30);

root = insert(root, 20);

root = insert(root, 40);

root = insert(root, 70);


root = insert(root, 60);

root = insert(root, 80);

// Traversals

printf("Inorder Traversal: ");

inorder(root); // Should print the values in sorted order

printf("\n");

printf("Preorder Traversal: ");

preorder(root); // Should print the root first, then left and right

printf("\n");

printf("Postorder Traversal: ");

postorder(root); // Should print left and right first, then root

printf("\n");

// Searching for a node

int searchValue = 40;

Node* foundNode = search(root, searchValue);

if (foundNode != NULL) {

printf("Node with value %d found in the tree.\n", foundNode->data);

} else {

printf("Node with value %d not found in the tree.\n", searchValue);

// Deleting a node

printf("Deleting node with value 20...\n");


root = deleteNode(root, 20);

printf("Inorder Traversal after deletion: ");

inorder(root);

printf("\n");

// Height of the tree

printf("Height of the tree: %d\n", height(root));

// Size of the tree

printf("Size of the tree: %d\n", size(root));

return 0;

Question 5. AVL Tree(Details)

AVL Tree
AVL Tree is invented by GM Adelson - Velsky and EM Landis in 1962. The tree is
named AVL in honour of its inventors.

AVL Tree can be defined as height balanced binary search tree in which each node is
associated with a balance factor which is calculated by subtracting the height of its right
sub-tree from that of its left sub-tree.

Tree is said to be balanced if balance factor of each node is in between -1 to 1,


otherwise, the tree will be unbalanced and need to be balanced.

Balance Factor (k) = height (left(k)) - height (right(k))


If balance factor of any node is 1, it means that the left sub-tree is one level higher than
the right sub-tree.

If balance factor of any node is 0, it means that the left sub-tree and right sub-tree
contain equal height.

If balance factor of any node is -1, it means that the left sub-tree is one level lower than
the right sub-tree.
An AVL tree is given in the following figure. We can see that, balance factor associated
with each node is in between -1 and +1. therefore, it is an example of AVL tree.

Complexity

Algorithm Average case Worst case

Space o(n) o(n)

Search o(log n) o(log n)

Insert o(log n) o(log n)

Delete o(log n) o(log n)

Operations on AVL tree


Due to the fact that, AVL tree is also a binary search tree therefore, all the operations are
performed in the same way as they are performed in a binary search tree. Searching and
traversing do not lead to the violation in property of AVL tree. However, insertion and deletion
are the operations which can violate this property and therefore, they need to be revisited.

SN Operation Description

Insertion in AVL tree is


performed in the same
way as it is performed in
a binary search tree.
However, it may lead to
1 Insertion violation in the AVL tree
property and therefore
the tree may need
balancing. The tree can
be balanced by applying
rotations.

Deletion can also be


2 Deletion performed in the same
way as it is performed in
a binary search tree.
Deletion may also
disturb the balance of the
tree therefore, various
types of rotations are
used to rebalance the
tree.

Why AVL Tree?


AVL tree controls the height of the binary search tree by not letting it to be skewed. The time
taken for all operations in a binary search tree of height h is O(h). However, it can be extended
to O(n) if the BST becomes skewed (i.e. worst case). By limiting this height to log n, AVL tree
imposes an upper bound on each operation to be O(log n) where n is the number of nodes.

AVL Rotations
We perform rotation in AVL tree only in case if Balance Factor is other than -1, 0, and 1.
There are basically four types of rotations which are as follows:

1. L L rotation: Inserted node is in the left subtree of left subtree of A


2. R R rotation : Inserted node is in the right subtree of right subtree of A
3. L R rotation : Inserted node is in the right subtree of left subtree of A
4. R L rotation : Inserted node is in the left subtree of right subtree of A

Where node A is the node whose balance Factor is other than -1, 0, 1.

The first two rotations LL and RR are single rotations and the next two rotations LR and
RL are double rotations. For a tree to be unbalanced, minimum height must be at least
2, Let us understand each rotation

1. RR Rotation
When BST becomes unbalanced, due to a node is inserted into the right subtree of the
right subtree of A, then we perform RR rotation, RR rotation is an anticlockwise rotation,
which is applied on the edge below a node having balance factor -2

In above example, node A has balance factor -2 because a node C is inserted in the
right subtree of A right subtree. We perform the RR rotation on the edge below A.
2. LL Rotation
When BST becomes unbalanced, due to a node is inserted into the left subtree of the
left subtree of C, then we perform LL rotation, LL rotation is clockwise rotation, which is
applied on the edge below a node having balance factor 2.

In above example, node C has balance factor 2 because a node A is inserted in the left
subtree of C left subtree. We perform the LL rotation on the edge below A.

3. LR Rotation
Double rotations are bit tougher than single rotation which has already explained above.
LR rotation = RR rotation + LL rotation, i.e., first RR rotation is performed on subtree and
then LL rotation is performed on full tree, by full tree we mean the first node from the
path of inserted node whose balance factor is other than -1, 0, or 1.

Advertisement

Let us understand each and every step very clearly:

State Action

A node B has been inserted into the


right subtree of A the left subtree of C,
because of which C has become an
unbalanced node having balance
factor 2. This case is L R rotation
where: Inserted node is in the right
subtree of left subtree of C
As LR rotation = RR + LL rotation,
hence RR (anticlockwise) on subtree
rooted at A is performed first. By doing
RR rotation, node A, has become the
left subtree of B.

After performing RR rotation, node C is


still unbalanced, i.e., having balance
factor 2, as inserted node A is in the
left of left of C

Now we perform LL clockwise rotation


on full tree, i.e. on node C. node C has
now become the right subtree of node
B, A is left subtree of B

Balance factor of each node is now


either -1, 0, or 1, i.e. BST is balanced
now.

4. RL Rotation
As already discussed, that double rotations are bit tougher than single rotation which
has already explained above. R L rotation = LL rotation + RR rotation, i.e., first LL
rotation is performed on subtree and then RR rotation is performed on full tree, by full
tree we mean the first node from the path of inserted node whose balance factor is other
than -1, 0, or 1.

State Action
A node B has been inserted into the
left subtree of C the right subtree of A,
because of which A has become an
unbalanced node having balance
factor - 2. This case is RL rotation
where: Inserted node is in the left
subtree of right subtree of A

As RL rotation = LL rotation + RR
rotation, hence, LL (clockwise) on
subtree rooted at C is performed first.
By doing RR rotation, node C has
become the right subtree of B.

After performing LL rotation, node A is


still unbalanced, i.e. having balance
factor -2, which is because of the right-
subtree of the right-subtree node A.

Now we perform RR rotation


(anticlockwise rotation) on full tree, i.e.
on node A. node C has now become
the right subtree of node B, and node
A has become the left subtree of B.
Balance factor of each node is now
either -1, 0, or 1, i.e., BST is balanced
now.

Advantages of AVL Tree:


1. AVL trees can self-balance themselves and therefore provides time
complexity as O(Log n) for search, insert and delete.
2. It is a BST only (with balancing), so items can be traversed in sorted
order.
3. Since the balancing rules are strict compared to Red Black Tree, AVL
trees in general have relatively less height and hence the search is
faster.
4. AVL tree is relatively less complex to understand and implement
compared to Red Black Trees.
Disadvantages of AVL Tree:
1. It is difficult to implement compared to normal BST and easier
compared to Red Black
2. Less used compared to Red-Black trees.
3. Due to its rather strict balance, AVL trees provide complicated insertion
and removal operations as more rotations are performed.
Applications of AVL Tree:
1. AVL Tree is used as a first example self balancing BST in teaching
DSA as it is easier to understand and implement compared to Red
Black
2. Applications, where insertions and deletions are less common but
frequent data lookups along with other operations of BST like sorted
traversal, floor, ceil, min and max.
3. AVL Trees can be used in a real time environment where predictable
and consistent performance is required.
Question 6. Graphs

Graph
A graph can be defined as group of vertices and edges that are used to connect these
vertices. A graph can be seen as a cyclic tree, where the vertices (Nodes) maintain any
complex relationship among them instead of having parent child relationship.

Definition
A graph G can be defined as an ordered set G(V, E) where V(G) represents the set of
vertices and E(G) represents the set of edges which are used to connect these vertices.
A Graph G(V, E) with 5 vertices (A, B, C, D, E) and six edges ((A,B), (B,C), (C,E), (E,D),
(D,B), (D,A)) is shown in the following figure.

Directed and Undirected Graph


A graph can be directed or undirected. However, in an undirected graph, edges are not
associated with the directions with them. An undirected graph is shown in the above
figure since its edges are not attached with any of the directions. If an edge exists
between vertex A and B then the vertices can be traversed from B to A as well as A to B.

Advertisement

In a directed graph, edges form an ordered pair. Edges represent a specific path from
some vertex A to another vertex B. Node A is called initial node while node B is called
terminal node.

A directed graph is shown in the following figure.


Graph Terminology

Path
A path can be defined as the sequence of nodes that are followed in order to reach
some terminal node V from the initial node U.

Closed Path
A path will be called as closed path if the initial node is same as terminal node. A path
will be closed path if V0=VN.

Simple Path
If all the nodes of the graph are distinct with an exception V0=VN, then such path P is
called as closed simple path.

Cycle
A cycle can be defined as the path which has no repeated edges or vertices except the
first and last vertices.

Connected Graph
A connected graph is the one in which some path exists between every two vertices (u,
v) in V. There are no isolated nodes in connected graph.

Complete Graph
A complete graph is the one in which every node is connected with all other nodes. A
complete graph contain n(n-1)/2 edges where n is the number of nodes in the graph.

Weighted Graph
In a weighted graph, each edge is assigned with some data such as length or weight.
The weight of an edge e can be given as w(e) which must be a positive (+) value
indicating the cost of traversing the edge.

Digraph
A digraph is a directed graph in which each edge of the graph is associated with some
direction and the traversing can be done only in the specified direction.

Loop
An edge that is associated with the similar end points can be called as Loop.

Adjacent Nodes
If two nodes u and v are connected via an edge e, then the nodes u and v are called as
neighbours or adjacent nodes.

Degree of the Node


A degree of a node is the number of edges that are connected with that node. A node
with degree 0 is called as isolated node.
A minimum spanning tree (MST) is defined as a spanning tree that has
the minimum weight among all the possible spanning trees.
The minimum spanning tree has all the properties of a spanning tree with
an added constraint of having the minimum possible weights among all
possible spanning trees. Like a spanning tree, there can also be many
possible MSTs for a graph.

Minimum Spanning Tree

Algorithms to find Minimum Spanning Tree:


There are several algorithms to find the minimum spanning tree from a
given graph, some of them are listed below:
Kruskal’s Minimum Spanning Tree Algorithm:
This is one of the popular algorithms for finding the minimum spanning
tree from a connected, undirected graph. The algorithm workflow is as
below:
 First, it sorts all the edges of the graph by their weights,
 Then starts the iterations of finding the spanning tree.
 At each iteration, the algorithm adds the next lowest-weight edge one
by one, such that the edges picked until now does not form a cycle.
This algorithm can be implemented efficiently using a DSU ( Disjoint-Set )
data structure to keep track of the connected components of the graph.
This is used in a variety of practical applications such as network design,
clustering, and data analysis.
Prim’s Minimum Spanning Tree Algorithm:
This is also a greedy algorithm. This algorithm has the following workflow:
 It starts by selecting an arbitrary vertex and then adding it to the MST.
 Then, it repeatedly checks for the minimum edge weight that connects
one vertex of MST to another vertex that is not yet in the MST.
 This process is continued until all the vertices are included in the MST.
To efficiently select the minimum weight edge for each iteration, this
algorithm uses priority_queue to store the vertices sorted by their
minimum edge weight currently. It also simultaneously keeps track of the
MST using an array or other data structure suitable considering the data
type it is storing.
This algorithm can be used in various scenarios such as image
segmentation based on color, texture, or other features. For Routing, as in
finding the shortest path between two points for a delivery truck to follow.
Applications of Minimum Spanning Trees:
 Network design: Spanning trees can be used in network design to find
the minimum number of connections required to connect all nodes.
Minimum spanning trees, in particular, can help minimize the cost of
the connections by selecting the cheapest edges.
 Image processing: Spanning trees can be used in image processing
to identify regions of similar intensity or color, which can be useful for
segmentation and classification tasks.
 Biology: Spanning trees and minimum spanning trees can be used in
biology to construct phylogenetic trees to represent evolutionary
relationships among species or genes.
 Social network analysis: Spanning trees and minimum spanning
trees can be used in social network analysis to identify important
connections and relationships among individuals or groups.
Breadth-First Search (BFS) and Depth-First Search (DFS) are two
fundamental algorithms used for traversing or searching graphs and trees.
This article covers the basic difference between Breadth-First Search and
Depth-First Search.


 Difference between BFS and DFS
Parameters BFS DFS

BFS stands for Breadth DFS stands for Depth First


Stands for First Search. Search.

BFS(Breadth First Search)


Data DFS(Depth First Search) uses
uses Queue data structure
Stack data structure.
Structure for finding the shortest path.

DFS is also a traversal


BFS is a traversal approach approach in which the traverse
in which we first walk begins at the root node and
through all nodes on the proceeds through the nodes as
same level before moving far as possible until we reach
on to the next level. the node with no unvisited
Definition nearby nodes.

Conceptual BFS builds the tree level by DFS builds the tree sub-tree by
Difference level. sub-tree.

Approach It works on the concept of It works on the concept of LIFO


used FIFO (First In First Out). (Last In First Out).

BFS is more suitable for DFS is more suitable when


searching vertices closer to there are solutions away from
Suitable for the given source. source.

BFS is used in various DFS is used in various


applications such as applications such as acyclic
bipartite graphs, shortest graphs and finding strongly
paths, etc. If weight of every connected components etc.
edge is same, then BFS There are many applications
gives shortest pat from where both BFS and DFS can
source to every other be used like Topological
Applications vertex. Sorting, Cycle Detection, etc.

You might also like