Data Structure Notes2-22
Data Structure Notes2-22
NOTES
2
DATA STRUCTURE
Introduction
Algorithm:
The algorithm word originated from the Arabic word “Algorism” which is linked to
the name of the Arabic mathematician AI Khwarizmi. He is considered to be the first
algorithm designer for adding numbers.
Input Step
Assignment Step
Decision Step
Repetitive Step
Output Step
Effectiveness: the operations of the algorithm must be basic enough to be put down
on pencil and paper. They should not be too complex to warrant writing another
algorithm for the operation.
Input-Output: The algorithm must have certain initial and precise inputs, and outputs
that may be generated both at its intermediate and final steps.
An algorithm does not enforce a language or mode for its expression but only
demands adherence to its properties.
DATA STRUCTURE
To save time (Time Complexity): A program that runs faster is a better program.
To save space (Space Complexity): A program that saves space over a competing
program is considerable desirable.
In computer terms, a data structure is a Specific way to store and organize data in a
computer's memory so that these data can be used efficiently later. Data may be
arranged in many different ways such as the logical or mathematical model for a
particular organization of data is termed as a data structure. The variety of a
particular data model depends on the two factors –
Secondly, the formation should be simple enough so that anyone can efficiently
process the data each time it is necessary.
A data structure is said to be linear if its elements combine to form any specific
order. There are basically two techniques of representing such linear structure within
memory.
First way is to provide the linear relationships among all the elements represented
by means of linear memory location. These linear structures are termed as arrays
. The second technique is to provide the linear relationship among all the elements
represented by using the concept of pointers or links. These linear structures are
termed as linked lists. The common examples of linear data structure are:
Arrays
Queues
Stacks
4
DATA STRUCTURE
Linked lists
This structure is mostly used for representing data that contains a hierarchical
relationship among various elements. Examples of Non Linear Data Structures are
listed below:
Graphs
In this case, data often contain a hierarchical relationship among various elements.
The data structure that reflects this relationship is termed as rooted tree graph or a
tree.
Graph: In this case, data sometimes hold a relationship between the pairs of
elements which is not necessarily following the hierarchical structure. Such data
structure is termed as a Graph.
The basic operations that are performed on data structures are as follows:
Searching: Searching involves searching for the specified data element in a data
structure.
Traversal: Traversal of a data structure means processing all the data elements
present in it.
Merging: Combining elements of two similar data structures to form a new data
structure of the same type, is called merging.
5
DATA STRUCTURE
Algorithm complexity
Efficiency of Algorithms:
The performances of algorithms can be measured on the scales of time and space.
The performance of a program is the amount of computer memory and time needed
to run a program. We use two approaches to determine the performance of a
program. One is analytical and the other is experimental. In performance analysis we
use analytical methods, while in performance measurement we conduct
experiments.
Analyzing Algorithms:
Suppose M is an algorithm, and suppose n is the size of the input data. Clearly the
complexity f(n) of M increases as n increases. It is usually the rate of increase of f(n)
with some standard functions. The most common computing times are
O(1), O(log2 n), O(n), O(n log2 n), O(n2), O(n3), O(2n)
Asymptotic Notations:
It is often used to describe how the size of the input data affects an algorithm’s
usage of computational resources. Running time of an algorithm is describe as a
function of input size n for large n.
DATA STRUCTURE
f(n) g(n)
3 2 3 3 f(n) = O(n )
16n + 45n n
+
12n
50 1 f(n) = O(1)
f(n) g(n)
3 2 3 3 f(n) = Ω(n
)
16n +8n + 2 n
DATA STRUCTURE
f(n) g(n)
7. 2n + 30n 2n f(n) = Θ
(2n)
8
DATA STRUCTURE
UNIT II
ARRAY
An array is a collection of similar data elements. These data elements have the same
data type.
The elements of the array are stored in consecutive memory locations and are
referenced by an
Declaring an array
Data type—the kind of values it can store, for example, Int, char, float, double.
The type can be either int, float, double, char, or any other valid data type. The
number within Brackets indicates the size of the array, i.e., the maximum number of
elements that can be stored In the array. For example, if we write,
int marks[10];
So on. Therefore, the last element, that is the 10th element, will be stored in marks
[9].
you can initialize an array in C either one by one or using a single statement as
follows −
9
DATA STRUCTURE
Double balance[5] = {1000.0, 2.0, 3.4, 7.0, 50.0};
The number of values between braces { } cannot be larger than the number of
elements that we declare for the array between square brackets [ ].
If you omit the size of the array, an array just big enough to hold the initialization is
created. Therefore, if you write −
You will create exactly the same array as you did in the previous example. Following
is an example to assign a single element of the array −
balance[4] = 50.0;
The above statement assigns the 5th element in the array with a value of 50.0. All
arrays have 0 as the index of their first element which is also called the base index
and the last index of an array will be total size of the array minus 1. Shown below is
the pictorial representation of the array we discussed above −
#include <stdio.h>
#include <conio.h>
int main()
int i, n, arr[20];
clrscr();
scanf("%d", &n);
for(i=0;i<n;i++)
{
10
DATA STRUCTURE
printf("\n arr[%d] = ", i);
scanf("%d",&arr[i]);
for(i=0;i<n;i++)
return 0;
Output
arr[0] = 1
arr[1] = 2
arr[2] = 3
arr[3] = 4
arr[4] = 5
#include <stdio.h>
#include <conio.h>
int main()
clrscr();
11
DATA STRUCTURE
printf("\n Enter the number of elements in the array : ");
scanf("%d", &n);
for(i=0;i<n;i++)
scanf("%d", &arr[i]);
scanf("%d", &num);
printf("\n Enter the position at which the number has to be added : ");
scanf("%d", &pos);
for(i=n–1;i>=pos;i––)
arr[i+1] = arr[i];
arr[pos] = num;
n = n+1;
for(i=0;i<n;i++)
getch();
return 0;
}
12
DATA STRUCTURE
Two Dimensional Array in C
data_type array_name[rows][columns];
int twodimen[4][3];
Initialization of 2D Array in C
In the 1D array, we don't need to specify the size of the array if the declaration and
initialization are being done simultaneously. However, this will not work with 2D
arrays. We will have to define at least the second dimension of the array. The two-
dimensional array can be declared and defined in the following way.
int arr[4][3]={{1,2,3},{2,3,4},{3,4,5},{4,5,6}};
#include <stdio.h>
#include <conio.h>
int main()
int i, j;
for(i=0;i<2;i++)
{
13
DATA STRUCTURE
printf("\n");
for(j=0;j<2;j++)
printf("%d\t", arr[i][j]);
return 0;
Output
12 34
56 32
#include <stdio.h>
#include <conio.h>
int main()
int i, j, mat[3][3];
clrscr();
for(i=0;i<3;i++)
for(j=0;j<3;j++)
scanf("%d",&mat[i][j]);
}
14
DATA STRUCTURE
}
for(i=0;i<3;i++)
printf("\n");
for(j=0;j<3;j++)
printf("\t %d",mat[i][j]);
return 0;
Output
123456789
123
456
789
#include <stdio.h>
#include <conio.h>
int main()
int i, j, k;
DATA STRUCTURE
int mat1[5][5], mat2[5][5], res[5][5];
clrscr();
scanf("%d",&rows1);
scanf("%d",&cols1);
scanf("%d",&rows2);
scanf("%d",&cols2);
if(cols1 != rows2)
getch();
exit();
res_rows = rows1;
res_cols = cols2;
for(i=0;i<rows1;i++)
for(j=0;j<cols1;j++)
{
16
DATA STRUCTURE
scanf("%d",&mat1[i][j]);
for(i=0;i<rows2;i++)
for(j=0;j<cols2;j++)
scanf("%d",&mat2[i][j]);
for(i=0;i<res_rows;i++)
for(j=0;j<res_cols;j++)
res[i][j]=0;
for(k=0; k<res_cols;k++)
for(i=0;i<res_rows;i++)
{
17
DATA STRUCTURE
printf("\n");
for(j=0;j<res_cols;j++)
printf("\t %d",res[i][j]);
return 0;
Output
1234
5678
19 22
43 50
Applications of Arrays
DATA STRUCTURE
and hash tables.
SPARSE MATRIX
In above example matrix, there are only 6 non-zero elements ( those are 9, 8, 4, 2, 5
& 2) and matrix size is 5 X 6. We represent this matrix as shown in the above image.
Here the first row in the right side table is filled with values 5, 6 & 6 which indicates
that it is a sparse matrix with 5 rows, 6 columns & 6 non-zero values. The second row
is filled with 0, 4, & 9 which indicates the non-zero value 9 is at the 0th-row 4th
19
DATA STRUCTURE
column in the Sparse matrix. In the same way, the remaining non-zero values also
follow a similar pattern.
DATA STRUCTURE
Unit III
LINKED LIST
A linked list is a linear collection of data elements, called nodes, where the linear
order is given by means of pointers. Each node is divided into two parts:
2. The second part contains the address of the next node (link /next pointer field) in
the list.
The data items in the linked list are not in consecutive memory locations. They may
be anywhere, but the accessing of these data items is easier as each data item
contains the address of the next data item.
2. A pointer to a node is represented by the relative position of the node within the
array.
Less number of nodes can be allocated which means that the program will
have overflow problem.
More number of nodes can be allocated which means that some amount of
the memory storage will be wasted.
4. The solution to this problem is to allow nodes that are dynamic, rather than static.
5. When a node is required storage is reserved /allocated for it and when a node is
no longer needed, the memory storage is released /freed.
DATA STRUCTURE
malloc() is a library function in <stdlib.h> header file.
2. The following lines allocate an integer space from the memory pointed by the
pointer p.
int *p;
p = (int *) malloc(sizeof(int));
Note that sizeof() is another library function that returns the number of bytes
required for the operand. In this example, 4 bytes for the int.
1. Linked lists are dynamic data structures. i.e., they can grow or shrink during the
execution of a program.
2. Linked lists have efficient memory utilization. Here, memory is not pre-allocated.
Memory is allocated whenever it is required and it is de-allocated (removed) when it
is no longer needed.
3. Insertion and Deletions are easier and efficient. Linked lists provide flexibility in
inserting a data item at a specified position and deletion of the data item from the
given position.
4. Many complex applications can be easily carried out with linked lists.
1. It consumes more space because every node requires a additional pointer to store
address of the next node.
DATA STRUCTURE
4. Circular Double Linked List.
A single linked list is one in which all nodes are linked together in some sequential
manner. Hence, it is also called as linear linked list.
A double linked list is one in which all nodes are linked together by multiple links
which helps in Accessing both the successor node (next node) and predecessor node
(previous node) from any arbitrary node within the list. Therefore, each node in a
double linked list has two link fields (pointers) to point to the left node (previous)
and the right node (next). This helps to traverse in forward direction and backward
direction.
A circular linked list is one, which has no beginning and no end. A single linked list
can be made a circular linked list by simply storing address of the very first node in
the link field of the last node.
A circular double linked list is one, which has both the successor pointer and
predecessor pointer in the circular manner.
The simplest kind of linked list is a singly-linked list, which has one link per node. This
link points to the next node in the list, or to a null value or empty list if it is the final
node.
A singly linked list's node is divided into two parts. The first part holds or points to
information about the node, and second part holds the address of next node. A
singly linked list travels one way.
Traversing a linked list means accessing the nodes of the list in order to perform
some processing on them. Remember a linked list always contains a pointer variable
23
DATA STRUCTURE
START which stores the address of the first node of the list. End of the list is marked
by storing NULL or –1 in the NEXT field of the last node. For traversing the linked list,
we also make use of another pointer variable PTR which points to the node that is
currently being accessed.
[END OF LOOP]
Step 5: EXIT
Searching a linked list means to find a particular element in the linked list. As already
discussed, a linked list consists of nodes which are divided into two parts, the
information part and the next part. So searching means finding whether a given
value is present in the information part of the node or not. If it is present, the
algorithm returns the address of the node that contains the value.
Go To Step 5
24
DATA STRUCTURE
ELSE
[END OF IF]
[END OF LOOP]
Step 5: EXIT
In this section, we will see how a new node is added into an already existing linked
list. We will
take four cases and then see how insertion is done in each case.
Before we describe the algorithms to perform insertions in all these four cases, let us
first discuss an important term called OVERFLOW. Overflow is a condition that occurs
when AVAIL = NULL or no free memory cell is present in the system. When this
condition occurs, the program must give an appropriate message.
Write OVERFLOW
Go to Step 7
[END OF IF]
DATA STRUCTURE
Step 4: SET DATA = VAL
Step 7: EXIT
Algorithm to insert a new node after a node that has value NUM
DATA STRUCTURE
In this section, we will discuss how a node is deleted from an already existing linked
list. We will consider three cases and then see how deletion is done in each case.
Write UNDERFLOW
Go to Step 5
[END OF IF]
Step 5: EXIT
Write UNDERFLOW
Go to Step 8
[END OF IF]
[END OF LOOP]
DATA STRUCTURE
Step 7: FREE PTR
Step 8: EXIT
Write UNDERFLOW
Go to Step 1
[END OF IF]
[END OF LOOP]
Write a program to create a linked list and perform insertions and deletions of all
cases.
#include<stdio.h>
#include<stdlib.h>
struct node
int data;
DATA STRUCTURE
};
void randominsert();
void begin_delete();
void last_delete();
void random_delete();
void display();
void search();
void main ()
while(choice != 9)
printf("\n\n*********Main Menu*********\n");
printf("\n===============================================\n");
scanf("\n%d",&choice);
29
DATA STRUCTURE
switch(choice)
case 1:
beginsert();
break;
case 2:
lastinsert();
break;
case 3:
randominsert();
break;
case 4:
begin_delete();
break;
case 5:
last_delete();
break;
case 6:
random_delete();
break;
case 7:
search();
break;
case 8:
30
DATA STRUCTURE
display();
break;
case 9:
exit(0);
break;
default:
void beginsert()
int item;
if(ptr == NULL)
printf("\nOVERFLOW");
else
printf("\nEnter value\n");
scanf("%d",&item);
ptr->data = item;
31
DATA STRUCTURE
ptr->next = head;
head = ptr;
printf("\nNode inserted");
void lastinsert()
int item;
if(ptr == NULL)
printf("\nOVERFLOW");
else
printf("\nEnter value?\n");
scanf("%d",&item);
ptr->data = item;
if(head == NULL)
head = ptr;
32
DATA STRUCTURE
printf("\nNode inserted");
else
temp = head;
temp->next = ptr;
ptr->next = NULL;
printf("\nNode inserted");
void randominsert()
int i,loc,item;
if(ptr == NULL)
printf("\nOVERFLOW");
33
DATA STRUCTURE
}
else
scanf("%d",&item);
ptr->data = item;
scanf("\n%d",&loc);
temp=head;
for(i=0;i<loc;i++)
temp = temp->next;
if(temp == NULL)
printf("\ncan't insert\n");
return;
printf("\nNode inserted");
}
34
DATA STRUCTURE
void begin_delete()
if(head == NULL)
printf("\nList is empty\n");
else
ptr = head;
head = ptr->next;
free(ptr);
void last_delete()
if(head == NULL)
printf("\nlist is empty");
{
35
DATA STRUCTURE
head = NULL;
free(head);
else
ptr = head;
while(ptr->next != NULL)
ptr1 = ptr;
ptr1->next = NULL;
free(ptr);
void random_delete()
int loc,i;
printf("\n Enter the location of the node after which you want to perform deletion
\n");
scanf("%d",&loc);
36
DATA STRUCTURE
ptr=head;
for(i=0;i<loc;i++)
ptr1 = ptr;
ptr = ptr->next;
if(ptr == NULL)
printf("\nCan't delete");
return;
free(ptr);
void search()
int item,i=0,flag;
ptr = head;
if(ptr == NULL)
printf("\nEmpty List\n");
37
DATA STRUCTURE
}
else
scanf("%d",&item);
while (ptr!=NULL)
if(ptr->data == item)
flag=0;
else
flag=1;
i++;
if(flag==1)
}
38
DATA STRUCTURE
}
void display()
ptr = head;
if(ptr == NULL)
printf("Nothing to print");
else
while (ptr!=NULL)
printf("\n%d",ptr->data);
Doubly linked list is a complex type of linked list in which a node contains a pointer to
the previous as well as the next node in the sequence. Therefore, in a doubly linked
list, a node consists of three parts: node data, pointer to the next node in sequence
(next pointer), pointer to the previous node (previous pointer).
39
DATA STRUCTURE
struct node
int data;
The prev part of the first node and the next part of the last node will always contain
null indicating end in each direction
Write a program to create a douby linked list and perform insertions and deletions of
all cases.
#include<stdio.h>
#include<stdlib.h>
struct node
int data;
};
40
DATA STRUCTURE
struct node *head;
void insertion_beginning();
void insertion_last();
void insertion_specified();
void deletion_beginning();
void deletion_last();
void deletion_specified();
void display();
void search();
void main ()
while(choice != 9)
printf("\n*********Main Menu*********\n");
printf("\n===============================================\n");
scanf("\n%d",&choice);
switch(choice)
{
41
DATA STRUCTURE
case 1:
insertion_beginning();
break;
case 2:
insertion_last();
break;
case 3:
insertion_specified();
break;
case 4:
deletion_beginning();
break;
case 5:
deletion_last();
break;
case 6:
deletion_specified();
break;
case 7:
search();
break;
case 8:
display();
break;
42
DATA STRUCTURE
case 9:
exit(0);
break;
default:
void insertion_beginning()
int item;
if(ptr == NULL)
printf("\nOVERFLOW");
else
scanf("%d",&item);
if(head==NULL)
{
43
DATA STRUCTURE
ptr->next = NULL;
ptr->prev=NULL;
ptr->data=item;
head=ptr;
else
ptr->data=item;
ptr->prev=NULL;
ptr->next = head;
head->prev=ptr;
head=ptr;
printf("\nNode inserted\n");
void insertion_last()
int item;
if(ptr == NULL)
{
44
DATA STRUCTURE
printf("\nOVERFLOW");
else
printf("\nEnter value");
scanf("%d",&item);
ptr->data=item;
if(head == NULL)
ptr->next = NULL;
ptr->prev = NULL;
head = ptr;
else
temp = head;
while(temp->next!=NULL)
temp = temp->next;
temp->next = ptr;
ptr ->prev=temp;
ptr->next = NULL;
}
45
DATA STRUCTURE
}
printf("\nnode inserted\n");
void insertion_specified()
int item,loc,i;
if(ptr == NULL)
printf("\n OVERFLOW");
else
temp=head;
scanf("%d",&loc);
for(i=0;i<loc;i++)
temp = temp->next;
if(temp == NULL)
DATA STRUCTURE
return;
printf("Enter value");
scanf("%d",&item);
ptr->data = item;
ptr->next = temp->next;
temp->next = ptr;
temp->next->prev=ptr;
printf("\nnode inserted\n");
void deletion_beginning()
if(head == NULL)
printf("\n UNDERFLOW");
head = NULL;
free(head);
47
DATA STRUCTURE
printf("\nnode deleted\n");
else
ptr = head;
free(ptr);
printf("\nnode deleted\n");
void deletion_last()
if(head == NULL)
printf("\n UNDERFLOW");
head = NULL;
free(head);
printf("\nnode deleted\n");
48
DATA STRUCTURE
}
else
ptr = head;
if(ptr->next != NULL)
free(ptr);
printf("\nnode deleted\n");
void deletion_specified()
int val;
printf("\n Enter the data after which the node is to be deleted : ");
scanf("%d", &val);
ptr = head;
{
49
DATA STRUCTURE
printf("\nCan't delete\n");
else
free(temp);
printf("\nnode deleted\n");
void display()
ptr = head;
while(ptr != NULL)
printf("%d\n",ptr->data);
ptr=ptr->next;
50
DATA STRUCTURE
}
void search()
int item,i=0,flag;
ptr = head;
if(ptr == NULL)
printf("\nEmpty List\n");
else
scanf("%d",&item);
while (ptr!=NULL)
if(ptr->data == item)
flag=0;
break;
else
51
DATA STRUCTURE
{
flag=1;
i++;
if(flag==1)
Queue
A Queue is a FIFO (First In First Out) data structure where the element that is added
first will be deleted first.
The basic queue operations are enqueue (insertion) and dequeue (deletion).
Enqueue is done at the front of the queue and dequeue is done at the end of the
queue. The elements in a queue are arranged sequentially and hence queues are
said to be linear data structures.
52
DATA STRUCTURE
The practical examples of queues are
Simple Queue
Circular Queue
Priority Queue
Dequeue (Double Ended Queue)
Simple Queue
The simple queue is a normal queue where insertion takes place at the FRONT of the
queue and deletion takes place at the END of the queue.
Circular Queue
Insertion in a circular queue happens at the FRONT and deletion at the END of the
queue.
Priority Queue
The node having the least priority will be the first to be removed from the priority
queue.
DATA STRUCTURE
Basic operations in a queue
The most basic queue operations in data structure are the following
enqueue() - Adds an element at the beginning of the queue. If the queue is full, then
it is an overflow.
dequeue() - Deletes an element at the end of the queue. If the queue is empty, then
it is an underflow.
enqueue()
dequeue()
Copy the element at the front of the queue to some temporary variable, TEMP =
QUEUE[ FRONT ].
Increment FRONT by 1.
Complexity
54
DATA STRUCTURE
Implementation of a queue
#include<stdio.h>
#define n 5
int main()
int queue[n],ch=1,front=0,rear=0,i,j=1,x=n;
while(ch)
scanf("%d",&ch);
switch(ch)
case 1:
if(rear==x)
else
scanf("%d",&queue[rear++]);
break;
55
DATA STRUCTURE
case 2:
if(front==rear)
else
x++;
break;
case 3:
if(front==rear)
else
printf("%d",queue[i]);
printf("\n");
break;
case 4:
56
DATA STRUCTURE
exit(0);
default:
return 0;
Circular Queue
A circular queue is the extended version of a regular queue where the last element is
connected to the first element. Thus forming a circle-like structure.
The circular queue solves the major limitation of the normal queue. In a normal
queue, after a bit of insertion and deletion, there will be non-usable empty space.
The following are the operations that can be performed on a circular queue:
enQueue(value): This function is used to insert the new value in the Queue. The new
element is always inserted from the rear end.
57
DATA STRUCTURE
deQueue(): This function deletes an element from the Queue. The deletion in a
Queue always takes place from the front end.
CPU Scheduling: The operating system also uses the circular queue to insert the
processes and then execute them.
Traffic system: In a computer-control traffic system, traffic light is one of the best
examples of the circular queue. Each light of traffic light gets ON one by one after
every jinterval of time. Like red light gets ON for one minute then yellow light for one
minute and then green light. After green light, the red light gets ON.
#include <stdio.h>
#define size 5
void deleteq(int[]);
void display(int[]);
int front = - 1;
int rear = - 1;
int main()
int n, ch;
int queue[size];
do
58
DATA STRUCTURE
{
scanf("%d", &ch);
switch (ch)
case 1:
scanf("%d", &n);
insertq(queue, n);
break;
case 2:
deleteq(queue);
break;
case 3:
display(queue);
break;
{
59
DATA STRUCTURE
if ((front == 0 && rear == size - 1) || (front == rear + 1))
printf("queue is full");
return;
else if (rear == - 1)
rear++;
front++;
rear = 0;
else
rear++;
queue[rear] = item;
int i;
60
DATA STRUCTURE
printf("\n");
else
if (front == - 1)
DATA STRUCTURE
{
front = - 1;
rear = - 1;
else
front++;
Stack
Basic Operations
Stack operations may involve initializing the stack, using it and then de-initializing it.
Apart from these basic stuffs, a stack is used for the following two primary
operations −
DATA STRUCTURE
To use a stack efficiently, we need to check the status of stack as well. For the same
purpose, the following functionality is added to stacks −
peek() − get the top data element of the stack, without removing it.
Stack is a LIFO(Last in First out) structure or we can say FILO(First in Last out).
push() function is used to insert new elements into the Stack and pop() function is
used to remove an element from the stack. Both insertion and removal are allowed
at only one end of Stack called Top.
Applications of Stack
The simplest application of a stack is to reverse a word. You push a given word to
stack - letter by letter - and then pop letters from the stack.
Parsing
Expression Conversion(Infix to Postfix, Postfix to Prefix etc)
#include<stdio.h>
int stack[100],choice,n,top,x,i;
void push(void);
void pop(void);
void display(void);
int main()
{
63
DATA STRUCTURE
//clrscr();
top=-1;
scanf("%d",&n);
printf("\n\t--------------------------------");
do
scanf("%d",&choice);
switch(choice)
case 1:
push();
break;
case 2:
pop();
break;
case 3:
64
DATA STRUCTURE
{
display();
break;
case 4:
break;
default:
while(choice!=4);
return 0;
void push()
if(top>=n-1)
DATA STRUCTURE
}
else
scanf("%d",&x);
top++;
stack[top]=x;
void pop()
if(top<=-1)
else
top--;
void display()
{
66
DATA STRUCTURE
if(top>=0)
printf("\n%d",stack[i]);
else
Unit IV
Root node: The topmost node in a tree data structure is known as a root node. A
root node is a node that does not have any parent.
DATA STRUCTURE
Child of a node: The immediate successor of a node is known as a child of a node.
Leaf node: The leaf node is a node that does not have any child node. It is also
known as an external node.
Non-leaf node: The non-leaf node is a node that has atleast one child node. It is also
known as an internal node.
Path: It is a sequence of the consecutive edges from a source node to the destination
node. Here edge is a link between two nodes.
Ancestor: The predecessor nodes that occur in the path from the root to that node is
known as an ancestor.
Descendant: The successor nodes that exist in the path from that node to the leaf
node.
Sibling: All the children that have the same parent node are known as siblings.
Depth of node: The length of the path from the root to that node is known as a
depth of a node.
Height of a node: The number of edges that occur in the longest path from that node
to the leaf node is known as the height of a node.
Level of node: The number of edges that exist from the root node to the given node
is known as a level of a node.
68
DATA STRUCTURE
Types of Trees
Types of trees depend on the number of children a node has. There are two major
tree types:
node has, is called a General tree. Examples are Family tree, Folder Structure.
Binary Tree: In a Binary tree, every node can have at most 2 children, left and
right. In diagram below, B & D are left children and C, E & F are right children.
Binary trees are further divided into many types based on its application.
Full Binary Tree: If every node in a tree has either 0 or 2 children, then the tree is
called a full tree. The tree in the above diagram is not a full binary tree as node C
has only the right child.
Perfect Binary tree: It is a binary tree in which all interior nodes have two
children and all leaves have the same depth or same level.
Balanced Tree: If the height of the left and right subtree at any node differs at
most by 1, then the tree is called a balanced tree.
69
DATA STRUCTURE
Binary Search Tree: It is a binary tree with binary search property. Binary search
property states that the value or key of the left node is less than its parent and
value or key of right node is greater than its parent. And this is true for all nodes.
Binary search trees are used in various searching and sorting algorithms. There
are many variants of binary search trees like AVL tree, B-Tree, Red-black tree, etc.
The binary search tree is a tree data structure that follows the condition of the binary
tree. As we know, that tree can have 'n' number of children, whereas; the binary tree
can contain the utmost two children. So, the constraint of a binary tree is also
followed by the binary search tree. Each node in a binary search tree should have the
utmost two children; in other words, we can say that the binary search tree is a
variant of the binary tree.
In Binary Search Tree, the middle element becomes the root node, the right part
becomes the right subtree, and the left part becomes the left subtree.
Binary search trees are a special kind of tree which follows the below rules,
70
DATA STRUCTURE
1. Every Node should have a unique key.
2. The key in the left node should be less than the parent key.
3. The key in the right node should be greater than the parent key
Traversal
There are 3 kinds of traversals that are done typically over a binary search tree. All
these traversals have a somewhat common way of going over the nodes of the tree.
In-order
This traversal first goes over the left subtree of the root node, then accesses the
current node, followed by the right subtree of the current node. The code represents
the base case too, which says that an empty tree is also a binary search tree.
// Base case
if (root == null) {
return;
inOrder(root.left);
DATA STRUCTURE
// Travel the right sub-tree next.
inOrder(root.right);
Pre-order
This traversal first accesses the current node value, then traverses the left and right
sub-trees respectively.
if (root == null) {
return;
preOrder(root.left);
preOrder(root.right);
Post-order
This traversal puts the root value at last, and goes over the left and right sub-trees
first. The relative order of the left and right sub-trees remain the same. Only the
position of the root changes in all the above mentioned traversals.
if (root == null) {
return;
DATA STRUCTURE
postOrder(root.left);
postOrder(root.right);
Graph
G= (V , E)
Here we are referring to an ordered pair because the first object must be the set of
vertices, and the second object must be a set of edges.
In Graph, each node has a different name or index to uniquely identify each node in
the graph. The graph shown below has eight vertices named as v1, v2, v3, v4, v5, v6,
v7, and v8. There is no first node, a second node, a third node and so on. There is no
ordering of the nodes.
An edge can be represented by the two endpoints in the graph. We can write the
name of the two endpoints as a pair, that represents the edge in a graph.
Directed edge: The directed edge represents one endpoint as an origin and another
point as a destination. The directed edge is one-way.
DATA STRUCTURE
The tree data structure contains only directed edges, whereas the graph can have
both types of edges, i.e., directed as well as undirected. But, we consider the graph
in which all the edges are either directed edges or undirected edges.
Directed graph: The graph with the directed edges known as a directed graph.
Undirected graph: The graph with the undirected edges known as a undirected
graph. The directed graph is a graph in which all the edges are uni-directional,
whereas the undirected graph is a graph in which all the edges are bi-directional.
Traversal of a graph
In this section we will see what is a graph data structure, and the traversal algorithms
of it.
The graph is one non-linear data structure. That is consists of some nodes and their
connected edges. The edges may be director or undirected. This graph can be
represented as G(V, E). The following graph can be represented as G({A, B, C, D, E},
{(A, B), (B, D), (D, E), (B, C), (C, A)})
74
DATA STRUCTURE
The graph has two types of traversal algorithms. These are called the Breadth First
Search and Depth First Search.
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.
Step 2 - Select any vertex as starting point for traversal. Visit that vertex and insert it
into the Queue.
Step 3 - Visit all the non-visited adjacent vertices of the vertex which is at front of the
Queue and insert them into the Queue.
Step 4 - When there is no new vertex to be visited from the vertex which is at front
of the Queue then delete that vertex.
Step 6 - When queue becomes empty, then produce final spanning tree by removing
unused edges from the graph
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.
75
DATA STRUCTURE
We use the following steps to implement DFS traversal...
Step 2 - Select any vertex as starting point for traversal. Visit that vertex and push it
on to the Stack.
Step 3 - Visit any one of the non-visited adjacent vertices of a vertex which is at the
top of stack and push it on to the stack.
Step 4 - Repeat step 3 until there is no new vertex to be visited from the vertex
which is at the top of the stack.
Step 5 - When there is no new vertex to visit then use back tracking and pop one
vertex from the stack.
Step 7 - When stack becomes Empty, then produce final spanning tree by removing
unused edges from the graph
Spanning tree
If we have a graph containing V vertices and E edges, then the graph can be
represented as: G(V, E)
If we create the spanning tree from the above graph, then the spanning tree would
have the same number of vertices as the graph, but the vertices are not equal. The
edges in the spanning tree would be equal to the number of edges in the graph
minus 1.
Normal graph
Some of the possible spanning trees that can be created from the above graph are:
76
DATA STRUCTURE
A minimum spanning tree is a spanning tree in which the sum of the weight of the
edges is as minimum as possible
Let's understand the above definition with the help of the example below.
Weighted graph
DATA STRUCTURE
The minimum spanning tree from the above spanning trees is:
78
DATA STRUCTURE