Data Structure
Data Structure
Data Structure
Data Structure
(MCA)
Nitasha Jain
Assistant Professor
Department of IT
Biyani Girls College, Jaipur
2
Published by :
Think Tanks
Biyani Group of Colleges
Edition : 2012
While every effort is taken to avoid errors or omissions in this Publication, any mistake or
omission that may have crept in is not intentional. It may be taken note of that neither the
publisher nor the author will be responsible for any damage or loss of any kind arising to
anyone in any manner on account of such errors and omissions.
Preface
I am glad to present this book, especially designed to serve the needs
of the students. The book has been written keeping in mind the general
weakness in understanding the fundamental concepts of the topics. The book
is self-explanatory and adopts the “Teach Yourself” style. It is based on
question-answer pattern. The language of book is quite easy and
understandable based on scientific approach.
Any further improvement in the contents of the book by making
corrections, omission and inclusion is keen to be achieved based on
suggestions from the readers for which the author shall be obliged.
I acknowledge special thanks to Mr. Rajeev Biyani, Chairman & Dr.
Sanjay Biyani, Director (Acad.) Biyani Group of Colleges, who are the
backbones and main concept provider and also have been constant source of
motivation throughout this endeavour. They played an active role in
coordinating the various stages of this endeavour and spearheaded the
publishing work.
I look forward to receiving valuable suggestions from professors of
various educational institutions, other faculty members and students for
improvement of the quality of the book. The reader may feel free to send in
their comments and suggestions to the under mentioned address.
Author
4
Syllabus
DATA STRUCTURE: Basic data structures such as arrays, stack and queues and their
applications, linked and sequential representation. Linked list, representation of linked
list, multi linked structures. Trees: definitions and basic concepts, linked tree
representation, representations in contiguous storage, binary trees, binary tree
traversal, searching insertion and deletion in binary trees, heap tree and heap sort
algorithm, AVL trees.
Reference Books
Introduction
A P P L E
101 102 103 104 105
P
P
Arrays
Q.1 What is an Array?
Ans An Array can be defined as a data structure having fixed size sequenced
collection of elements of same data type and which can be referenced
through same variable name. An Array is a name given to a group of
similar quantities.
Declaring an array
Type variable_name [length of array];
For example:-
double height[10];
float width[20];
int min[9];
int myArray[5] = {1, 2, 3, 4, 5}; //declare and initialize the array in one
statement
In C language array starts at position 0. C language treats array name as the
pointer to the first element and an iten in the array can be accessed through
its index.
// Reading an array
printf(“Enter size of an array”);
scanf ("%d", &n);
printf(“Enter array elements”);
for (i=0;i<n;i++)
scanf ("%d", &array[i]);
// writing an array
printf(“array elements are”);
for (i=0;i<n;i++)
printf ("%d", array[i]);
}
Ans To insert a value into an array, you need to shift every value after the
location you want to insert. the logic is very simple: start from the end and
copy the previous item to the current element until you hit the location you
want to insert.
// Reading an array
printf (“Enter size of an array”);
scanf ("%d", &n);
printf (“Enter array elements”);
for (i=0;i<n;i++)
scanf ("%d", &array[i]);
// writing an array
printf (“array elements are”);
for (i=0;i<n;i++)
printf ("%d", array[i]);
}
#include<stdio.h>
void main ()
{
int array[10], n elem ,pos;
// Reading an array
printf(“Enter size of an array”);
scanf ("%d", &n);
printf(“Enter array elements”);
for (i=0;i<n;i++)
scanf ("%d", &array[i]);
// writing an array
printf(“array elements are”);
for (i=0;i<n;i++)
printf ("%d", array[i]);
}
void main()
{
int a[20],b[20],c[40],n,m,i,p;
printf(“\nEnter the no.of element present in the first array: “);
scanf(“%d”,&n);
printf(“\nEnter the first array…….\n”);
for(i=0;i<n;i++)
scanf(“%d”,&a[i]);
printf(“\nEnter the no. of element present in the second array:
“);
scanf(“%d”,&m);
printf(“\nEnter the second array…….\n”);
for(i=0;i<m;i++)
scanf(“%d”,&b[i]);
p=merge(a,b,c,n,m);
printf(“\nThe merged array is………\n”);
for(i=0;i<p;i++)
printf(“%d “,c[i]);
printf(“\n\n”);
}
int merge(int a[],int b[],int c[],int n,int m)
{
int i=0,j=0,k=0;
while(i<n&&j<m)
{
if(a[i]<b[j])
{
c[k]=a[i];
i++;
k++;
}
else if(a[i]>b[j])
{
c[k]=b[j];
j++;
k++;
}
else // to avoid duplication
{
c[k]=a[i];
i++;
j++;
k++;
}
10
}
for(;i<n;i++,k++)
c[k]=a[i];
for(;j<m;j++,k++)
c[k]=b[j];
return k;
}
void main()
{
int a[3][2];
int i,j;
for(i = 0;i<3;i++){
for(j=0;j<2 ;j++) {
a[i][j]=2;
}
Data Structure 11
for(i = 0;i<3;i++){
for(j=0;j<2;j++) {
printf("value in array %d\n",a[i][j]);
}
}
for(i = 0;i<3;i++){
for(j=0;j<2;j++){
printf("value in array %d and address is %8u\n", a[i][j],&a[i][j]);
}
}
}
Where 1 ≤ i ≤ m and 1 ≤ j ≤ n
For example:
Suppose two matrixes A and B of size of 2 x 2 and 2 x 3 respectively:
12
9. Exit
Explanation: First we check whether the rows of A are equal to columns of B
or the columns of A are equal to rows of B. If they are not equal, then
multiplication is not possible. But, if they are equal, the first for loop iterates
to total number of columns of A i.e. N and the second for loop iterates to the
total number of rows of B i.e. X.
In step 6, all the elements of C are set to zero. Then the third for loop iterates
to total
number of columns of B i.e. Y.
In step 8, the element A[I][K] is multiplied with B[K][J] and added to C[I][J]
and the result is assigned to C[I][J] by the statement:
C[I][J] = C[I][J] + A[I][K] * B[K][J]
#include<stdio.h>
void main()
{
int a[5][5],b[5][5],c[5][5],i,j,k,sum=0,m,n,o,p;
printf("\nEnter the row and column of first matrix");
scanf("%d %d",&m,&n);
printf("\nEnter the row and column of second matrix");
scanf("%d %d",&o,&p);
if(n!=o){
printf("Matrix mutiplication is not possible");
printf("\nColumn of first matrix must be same as row of second matrix");
}
else{
printf("\nEnter the First matrix->");
for(i=0;i<m;i++)
for(j=0;j<n;j++)
scanf("%d",&a[i][j]);
printf("\nEnter the Second matrix->");
for(i=0;i<o;i++)
for(j=0;j<p;j++)
scanf("%d",&b[i][j]);
printf("\nThe First matrix is\n");
for(i=0;i<m;i++){
printf("\n");
for(j=0;j<n;j++){
14
printf("%d\t",a[i][j]);
}
}
printf("\nThe Second matrix is\n");
for(i=0;i<o;i++){
printf("\n");
for(j=0;j<p;j++){
printf("%d\t",b[i][j]);
}
}
for(i=0;i<m;i++)
for(j=0;j<p;j++)
c[i][j]=0;
for(i=0;i<m;i++){ //row of first matrix
for(j=0;j<p;j++){ //column of second matrix
sum=0;
for(k=0;k<n;k++)
sum=sum+a[i][k]*b[k][j];
c[i][j]=sum;
}
}
}
printf("\nThe multiplication of two matrix is\n");
for(i=0;i<m;i++){
printf("\n");
for(j=0;j<p;j++){
printf("%d\t",c[i][j]);
}
}
getch();
}
#include<stdio.h>
void main(){
int a[10][10],i,j,sum=0,m,n;
scanf("%d %d",&m,&n);
for(i=0;i<m;i++){
printf("\n");
for(j=0;j<m;j++){
printf("%d\t",a[i][j]);
}
}
for(i=0;i<m;i++){
for(j=0;j<n;j++){
if(i==j)
sum=sum+a[i][j];
}
}
printf("\n\nSum of the diagonal elements of a matrix is: %d",sum);
getch();
}
output:
2 6 7
Sum of the diagonal elements of a matrix is: 16
Explanation
We can observer the properties any element Aij will diagonal element if
and only if i = j
Data Structure 17
Searching
#include <stdio.h>
#include <conio.h>
void main()
{
int array[10];
int i, N, keynum, found=0;
clrscr();
}
if ( found == 1)
printf("SUCCESSFUL SEARCH\n");
else
printf("Search is FAILED\n");
} /* End of main */
void main()
{
int array[10];
int i, n, elem, found=0;
clrscr();
} /* End of main */
20
Stack
int stack[MAXSIZE];
int top; //index pointing to the top of stack
void main()
{
void push(int);
int pop();
int will=1,i,num;
while(will ==1)
Data Structure 21
{
printf("MAIN MENU:
1.Add element to stack
2.Delete element from the stack
");
Scanf ("%d", &will);
switch(will)
{
case 1: printf("Enter the data... ");
scanf("%d", &num);
push(num);
break;
case 2: num=pop();
printf("Value returned from pop function is %d ",num);
break;
default: printf ("Invalid Choice . ");
}
printf(“Do you want to do more operations on Stack ( 1 for yes, any other
key to exit) ");
scanf("%d" , &will);
} //end of outer while
} //end of main
void push(int elem)
{
if(isfull())
{
printf("STACK FULL");
return;
}
top++;
stack[top]=elem;
}
}
int pop()
{
int a;
if(isEmpty())
{
printf("STACK EMPTY");
return 0;
}
a=stack[top];
22
top--;
}
return(a);
}
int isFull()
{
if(top> MAXSIZE)
return 0;
else
return 1;
}
int isEmpty()
{
if(top<=0)
return 0;
else
return 1;
}
In Infix notation, the arithmetic operator appears between the two operands to
which it is being applied. For example: - A / B + C
POSTFIX NOTATION
The arithmetic operator appears directly after the two operands to which it
applies. also called reverse polish notation. ((A/B) + C)For example: - AB / C
+
PREFIX NOTATION
The arithmetic operator is placed before the two operands to which it applies.
Also called as polish notation. ((A/B) + C)For example: - +/ABC
INFIX PREFIX (or) POLISH POSTFIX (or) REVERSEPOLISH
1. (A + B) / (C - D) /+AB - CD AB + CD - /
2. A + B*(C - D) +A*B - CD ABCD - * +
3. X * A / B - D - / * XABD X A*B/D-
4. X + Y * (A - B) / +X/*Y - AB - CD XYAB - *CD - / +(C - D)
5. A * B/C + D + / * ABCD AB * C / D +
A+B*C-D/E
b) + B * C - D / E A
c) B * C - D / E + A
d) *C-D/E + AB
e) C-D/E +* AB
f) -D/E +* ABC
g) D/E +- ABC*
h) /E +- ABC*D
i) E +-/ ABC*D
j) +-/ ABC*DE
k) ABC*DE/-+
void towers(int,char,char,char);
void main()
{
int n;
clrscr();
printf("Enter the no.of elements:");
scanf("%d",&n);
towers(n,'a','c','b');
getch();
}
void towers(int n,char frompeg,char topeg,char auxpeg)
{
if(n==1)
{
printf("\n%s%c\t%s%c","movedisk1 frompeg",frompeg,"topeg",topeg);
return;
}
towers(n-1,frompeg,auxpeg,topeg);
printf("\n%s%d\t%s%c\t%s%c","movedisk",n,"frompeg",frompeg,"top
eg",topeg);
towers(n-1,auxpeg,topeg,frompeg);
}
26
Queue
While dealing with the circular queue we will use the following assumptions :
1. Front will always be pointing to the first element of the queue.
2. Each time a new element is inserted into the queue, the value of rear is
incremented by one i.e., Rear = (Rear + 1);
3. Each time when an existing element is deleted from the queue, the value
of rear is incremented by one i.e., Front = (Front + 1);
4. Front is the initial or first location of the queue where Rear indicates the last
entry location in the queue.
Ans
#include <stdio.h>
#include<ctype.h>
# define MAXSIZE 200
int queue[MAXSIZE];
int front=-1, rear=-1; //index pointing to the top of stack
void main()
{
void enqueue(int);
int dequeue();
int will=1,i,num,ch;
while(will ==1)
{
printf("MAIN MENU:
1. Enqueue
2.Dequeue
3. Check Queue Full
4. Check Queue Empty ");
switch(ch)
{
case 1: printf("Enter the data to add... ");
scanf("%d", &num);
enqueue(num);
break;
case 2: num=dequeue();
if(num==-1)
printf(“Queue is empty”);\
else
printf("Value returned from pop function is %d
",num);
break;
case 3 : isFull();
break;
case 4 : isEmpty();
break;
default: printf ("Invalid Choice . ");
}
printf(“Do you want to do more operations on Stack ( 1 for yes, any other
key to exit) ");
scanf("%d" , &will);
28
return 0;
else
return 1;
}
int queue[MAXSIZE];
int front=-1, rear=-1; //index pointing to the top of stack
void main()
{
void enqueue(int);
int dequeue();
int will=1,i,num,ch;
while(will ==1)
{
printf("MAIN MENU:
1. Enqueue
2.Dequeue
3. Check Queue Full
4. Check Queue Empty ");
switch(ch)
{
case 1: printf("Enter the data to add... ");
scanf("%d", &num);
30
enqueue(num);
break;
case 2: num=dequeue();
if(num= = -1)
printf(“Queue is empty”);\
else
printf("Value returned from pop function is %d
",num);
break;
case 3 : isFull();
break;
case 4 : isEmpty();
break;
default: printf ("Invalid Choice . ");
}
printf(“Do you want to do more operations on Stack ( 1 for yes, any other
key to exit) ");
scanf("%d" , &will);
} //end of outer while
} //end of main
{
elem=queue[front];
if (front==rear)
front=rear=-1;
else
front= (front+1) % MAXSIZE ;
}
return(elem);
}
int isFull()
{
If(((front==0) && (rear==MAXSIZE-1)) || (front=rear+1))
return 0;
else
return 1;
}
int isEmpty()
{
if((front==-1) && (front==rear))
return 0;
else
return 1;
}
This algorithm deleted and processes the first element in a priority queue
maintained by a 2-dimensional array Queue
1. [Find the first nonempty queue]
Find the smallest K such that FRONT[K]!=NULL.
2. Delete and process the front element in row K of Queue.
3. Exit.
Data Structure 33
Sorting
Q.1 What is selection sort?
Ans: This is the simplest sorting method. In order to sort data in ascending order,
the 1st element is compared to all other elements and if found greater than the
compared element, then they are interchanged. So after the first iteration the
smallest element is placed at the 1st position. The same procedure is repeated
for the 2nd element and so on for all the elements.
Example: Selection Sort
5 1 3 7 2 find min
1 5 3 7 2 swap to index 0
1 5 3 7 2 find min
1 2 3 7 5 swap to index 1
1 2 3 7 5 find min
1 2 3 7 5 swap to index 2
1 2 3 7 5 find min
1 2 3 5 7 swap to index 3
}
if ( min != i )
{
swap = array[i];
array[i] = array[min];
array[min] = swap;
}
}
printf("Sorted list in ascending order:\n");
for ( i = 0 ; i < size ; i++ )
printf("%d\n", array[i]);
return 0;
}
For Example
Let us take the array of numbers "5 1 4 2 8", and sort the array from lowest
number to greatest number using bubble sort algorithm. In each step, elements
written in bold are being compared. Three passes will be required.
First Pass:
( 5 1 4 2 8 ) ( 1 5 4 2 8 ), Here, algorithm compares the first two elements,
and swaps them.
( 1 5 4 2 8 ) ( 1 4 5 2 8 ), Swap since 5 > 4
( 1 4 5 2 8 ) ( 1 4 2 5 8 ), Swap since 5 > 2
( 1 4 2 5 8 ) ( 1 4 2 5 8 ), Now, since these elements are already in order (8
> 5), algorithm does not swap them.
Second Pass:
(14258) (14258)
( 1 4 2 5 8 ) ( 1 2 4 5 8 ), Swap since 4 > 2
(12458) (12458)
(12458) (12458)
Now, the array is already sorted, but our algorithm does not know if it is
Data Structure 35
completed. The algorithm needs one whole pass without any swap to know it
is sorted.
Third Pass:
(12458) (12458)
(12458) (12458)
(12458) (12458)
(12458) (12458)
main()
{
int arr[MAX], i, j, k, temp, size, xchanges;
printf("Enter the number of elements : ");
scanf("%d",&n);
printf("Enter array element”);
for (i = 0; i < n; i++)
scanf("%d",&arr[i]);
/* Bubble sort*/
for (i = 1; i < n ; i++)
{
for (j = 0; j <n-1-i; j++)
{
if (arr[j] > arr[j+1])
{
temp = arr[j];
arr[j] = arr[j+1];
arr[j+1] = temp;
}/*End of if*/
}/*End of inner for loop*/
1. Divide the unsorted list into two sublists of about half the size
2. Divide each of the two sublists recursively until we have list sizes of
length 1, in which case the list itself is returned
3. Merge the two sorted sublists back into one sorted list.
For Example
Data Structure 39
}
void mergesort(int a[], int low, int high)
{
int mid;
if(low<high)
{
mid=(low+high)/2;
mergesort(a,low,mid);
mergesort(a,mid+1,high);
40
merge(a,low,high,mid);
}
}
merge(int a[], int low, int high, int mid)
{
int i, j, k, c[50];
i=low;
j=mid+1;
k=low;
while((i<=mid)&&(j<=high))
{
if(a[i]<a[j])
{
c[k]=a[i];
k++;
i++;
}
else
{
c[k]=a[j];
k++;
j++;
}
}
while(i<=mid)
{
c[k]=a[i];
k++;
i++;
}
while(j<=high)
{
c[k]=a[j];
k++;
j++;
}
for(i=low;i<k;i++)
{
a[i]=c[i];
}
}
Q.10 What is Merge sort?
Ans : The divide-and-conquer strategy is used in quicksort. Below the recursion step
is described:
Data Structure 41
1. Choose a pivot value. We take the value of the middle element as pivot value,
but it can be any value, which is in range of sorted values, even if it doesn't
present in the array.
2. Partition. Rearrange elements in such a way, that all elements which are
lesser than the pivot go to the left part of the array and all elements greater
than the pivot, go to the right part of the array. Values equal to the pivot can
stay in any part of the array. Notice, that array may be divided in non-equal
parts.
3. Sort both parts. Apply quicksort algorithm recursively to the left and the
right parts.
There are two indices i and j and at the very beginning of the partition algorithm i
points to the first element in the array and j points to the last one. Then algorithm
moves i forward, until an element with value greater or equal to the pivot is found.
Index j is moved backward, until an element with value lesser or equal to the pivot
is found. If i ≤ j then they are swapped and i steps to the next position (i + 1), j
steps to the previous one (j - 1). Algorithm stops, when i becomes greater than j.
After partition, all values before i-th element are less or equal than the pivot and
all values after j-th element are greater or equal to the pivot.Example. Sort {1, 12,
5, 26, 7, 14, 3, 7, 2} using quicksort.
42
int i = low ;
int j = high ;
int temp=0;
int pivot = a[(left+right)/2];
do
{
while (a[i] < pivot)
i++;
while (a[j] > pivot)
j--;
if (i <= j)
{
temp = a[i];
a[i] = a[j];
a[j] = temp;
i++;
j--;
}
}while (i <= j);
if (low < j)
quickSort (a, low, j);
if (i < high)
quickSort (a, i , high);
}
void main()
{
int array[]={12,99,4,99,12,12,13,10,13};
printf("Before sort:\n\n");
print(array);
quickSort(array,0,8);
printf("\n\nAfter sort:\n\n");
print(array);
printf("");
}
44
Linked List
For Example :
Linked Representation
Q.4 Write a ‘C’ code to create and traverse a linear linked list?
Ans: To create a linked list at first we need to design the structure of node i.e. what
kind of data it is having. After creating node we will make a start node.
#include<conio.h>
#include<stdio.h>
void creation(int);
void display();
typedef struct linkedlist
Data Structure 47
{
int num;
struct linkedlist *next;
}node;
Node *head=NULL,*p=NULL;
void main()
{
int n1,ch;
clrscr();
printf("enter the no of nodes to be entered : ");
scanf("%d",&n1);
do
{
clrscr();
printf("\n1.creation\n2.insertion\n3.deletion\n4.display\n5.exit\n");
printf("\nenter ur choice : ");
scanf("%d",&ch);
switch(ch)
{
case 1:
creation(n1);
break;
case 2:
display();
getch();
break;
case 3:
exit(0);
}
}while(ch!=3);
getch();
}
/* CREATION */
void creation(int n1)
{
int i, n ;
head=((struct list *) malloc(sizeof(struct list)));
p=head;
for(i=0;i<n1;i++)
{
printf("enter the %d node : ",i+1);
scanf("%d",&n);
48
p->num = n;
p->next = ((struct list *)malloc(sizeof(struct list)));
p=p->next;
}
p->next=0;
}
/* DISPLAY */
void display()
{
p=head;
printf("\nthe nodes entered are : ");
while(p->next>0)
{
printf ("%d\t", p->num);
p=p->next;
}
}
Q.6 Write a ‘C’ code to insert a node in first position in a linear linked list?
Ans:
#include<stdio.h>
#include<stdlib.h>
#include<conio.h>
Data Structure 49
#include<math.h>
void main()
{
node* create(node*);
void display(node*);
node* insert_beg(node*,int);
node* delete_first(node*);
node *head=NULL;
int x;
clrscr();
head=create(head);
display(head);
printf("\nenter element to insert");
scanf("%d",&x);
head=insert_beg(head,x);
printf("\ncreated link list is :");
display(head);
getch();
}
node* getnode(int);
node *p,*q;
p=getnode(x);
q=head;
if(head==NULL)
head=p;
else
{
while(q->next!=NULL)
q=q->next;
q->next=p;
}
return(head);
}
node* insert_beg(node *head,int x)
{
node* getnode(int x);
node *p;
p=getnode(x);
if(head==NULL)
head=p;
else
{
p->next=head;
head=p;
}
return(head);
}
node* getnode(int x)
{
node *p;
p=(node*)malloc(sizeof(node));
p->data=x;
p->next=NULL;
return(p);
}
void display(node *head)
{
node *p;
printf("\nvalues of the entered list is:");
p=head;
while(p!=NULL)
{
printf("%d",p->data);
Data Structure 51
p=p->next;
}
node *p;
p=head;
while(p!=NULL)
{
p=p->next;
}
}
Q.7 How to delete a node from a first position in linear linked list?
Ans: Algorithm:-
Step-1: Take the value in the 'node value' field of the TARGET node in any
intermediate variable
Step-2: Make the previous node of TARGET to point to where TARGET is
pointing
Step-3: Free the TARGET
Step-4: Return the value in that intermediate variable
#include<stdio.h>
#include<stdlib.h>
#include<conio.h>
#include<math.h>
void main()
{
node* create(node*);
void display(node*);
node* insert_beg(node*,int);
node* delete_first(node*);
node *head=NULL;
int x;
clrscr();
head=create(head);
display(head);
52
head=delete_first(head);
display(head);
getch();
}
node* getnode(int x)
{
node *p;
p=(node*)malloc(sizeof(node));
p->data=x;
p->next=NULL;
return(p);
}
void display(node *head)
{
node *p;
printf("\nvalues of the entered list is:");
p=head;
while(p!=NULL)
{
printf("%d",p->data);
p=p->next;
}
}
Note that
Each node point to previous node and next node.
Since there is no node before first node, so first node's llink contains null.
Similarly, for the last node. There is no node after last node, hence last node's rlink
contains null.
However ,if the list is initially not empty, then the element is inserted as the first
element of the list by performing the following steps :
Assign value of the head variable (the address of the first element of the
existing list) to the next pointer field of the new node.
Assigning address of the new node to the previous pointer field of the node
currently pointed by „head‟ variable i.e., first element of the existing list
Finally, assign the address of the new node to head variable
However ,if the list is initially not empty, then the element is inserted as
the first element of the list by performing the following steps :
Assign value of the tail variable (the address of the last element of the
existing list) to the previous pointer field of the new node.
56
Assigning address of the new node to the next pointer field of the node
currently pointed by „tail‟ variable i.e., last element of the existing list
Finally, assign the address of the new node to „tail‟ variable
Ans: To delete an element from the list, first the pointers are set properly and then
the memory occupied by the node to be deleted is deallocated (free).
Deletion in the list can take place at the following positions.
At the beginning of the list
At the end of the list
After a given element
Before a given element
Trees
Q.1 What is Tree Data Structure?
Ans:
A tree is called non-linear data structure because the elements of this data
structure are arranged in a non-linear fashion i.e., they use two dimensional
representation.
The tree data structure is most suitable where the hierarchy relationship among
data are to be maintained.
Advantage of this data structure is that insertion, deletion, searching etc., are
more efficient than linear data structures
Definition
A tree is a collection of elements called nodes, one of which is designated as
root along with a relation that places a hierarchical structure on the nodes.
Parent
The parent of a node is the immediate predecessor of that node.
A is the parent nodes B and C
Child
The immediate successors of a node are called child nodes.
In fig ., B and C are the child nodes of A.
A child which is placed at the left side is called the left child
A child which is placed at the right side is called the right child
Root
A root is a specially designated node in a tree
It is a node which has no parent.
In fig., the node A is the root of the tree
There can be only one root node in a tree
Level
The level of a node in the tree is the rank of the hierarechy.
The root node is placed in level 0.
Data Structure 63
If a node is at level L the its child is at level L+1 and its parent is at
level L-1
Additional Question
Structures Aptitude
Q.1 What is data structure?
Ans: A data structure is a way of organizing data that considers not only the items
stored, but also their relationship to each other. Advance knowledge about the
relationship between data items allows designing of efficient algorithms for
the manipulation of data.
Q.2 List out the areas in which data structures are applied extensively?
Ans
Compiler Design, Operating System, Database Management System,
Q.3 What are the major data structures used in the following areas : RDBMS,
Network data model & Hierarchical data model.
Ans
RDBMS – Array (i.e. Array of structures)
Network data model – Graph
Hierarchical data model – Trees
Q.4 If you are using C language to implement the heterogeneous linked list,
what pointer type will you use?
Ans The heterogeneous linked list contains different data types in its nodes and we
need a link, pointer to connect them. It is not possible to use ordinary pointers
for this. So we go for void pointer. Void pointer is capable of storing pointer
to any type as it is a generic pointer type.
Q.7 What are the notations used in Evaluation of Arithmetic Expressions using
prefix and postfix forms?
Ans Polish and Reverse Polish notations.
21
Let us take a tree with 5 nodes (n=5)
Null Branches
For example, consider a tree with 3 nodes(n=3), it will have the maximum
combination of 5 different (ie, 23 - 3 = 5) trees.
i ii iii iv v
In general:
If there are n nodes, there exist 2n-n different trees.
Q.11 List out few of the applications that make use of Multilinked Structures?
Ans
Sparse matrix, Index generation.
Q.13 What is the type of the algorithm used in solving the 8 Queens problem?
Ans Backtracking
Q.15 What is the bucket size, when the overlapping and collision occur at same
time?
Ans One. If there is only one entry possible in the bucket, when the collision
occurs, there is no way to accommodate the colliding value. This results in the
overlapping of values.
Data Structure 67
Q.16 Traverse the given tree using Inorder, Preorder and Postorder traversals.
Ans
Given tree:
A
B C
D E F G
H I J
Inorder : D H B E A F C I G J
Preorder: A B D H E C F G I J
Postorder: H D E B F I J G C A
Q.17 There are 8, 15, 13, 14 nodes were there in 4 different trees. Which of them
could have formed a full binary tree?
Ans 15.
In general:
There are 2n-1 nodes in a full binary tree.
By the method of elimination:
Full binary trees contain odd number of nodes. So there cannot be full
binary trees with 8 or 14 nodes, so rejected. With 13 nodes you can
form a complete binary tree but not a full binary tree. So the correct
answer is 15.
Note:
Full and Complete binary trees are different. All full binary trees are complete
binary trees but not vice versa.
Q.18 In the given binary tree, using array you can store the node 4 at which
location?
Ans
2 3
4
68
At location 6
1 2 3 - - 4 - - 5
where LCn means Left Child of node n and RCn means Right Child of node n
65 70 75 80 85 60 55 50 45
Sorting takes place from the pivot value, which is the first value of the given
elements, this is marked bold. The values at the left pointer and right pointer
are indicated using L and R respectively.
65 70L 75 80 85 60 55 50 45R
Since pivot is not yet changed the same process is continued after
interchanging the values at L and R positions
65 45 75 L 80 85 60 55 50 R 70
65 45 50 80 L 85 60 55 R 75 70
65 45 50 55 85 L 60 R 80 75 70
65 45 50 55 60 R 85 L 80 75 70
When the L and R pointers cross each other the pivot value is interchanged
with the value at right pointer. If the pivot is changed it means that the pivot
has occupied its original position in the sorted order (shown in bold italics)
Data Structure 69
and hence two different arrays are formed, one from start of the original array
to the pivot position-1 and the other from pivot position+1 to end.
60 L 45 50 55 R 65 85 L 80 75 70 R
55 L 45 50 R 60 65 70 R 80 L 75 85
50 L 45 R 55 60 65 70 80 L 75 R 85
45 50 55 60 65 70 75 80 85
Q.20 For the given graph, draw the DFS and BFS?
Ans
DFS: A X H P E Y M J G
Q.20 Classify the Hashing Functions based on the various methods by which the
key value is found.
Ans
Direct method,
Subtraction method,
Modulo-Division method,
Digit-Extraction method,
Mid-Square method,
Folding method,
Pseudo-random method.
70
Q.21 What are the types of Collision Resolution Techniques and the methods used
in each of the type?
Ans
Open addressing (closed hashing),
The methods used include:
Overflow block,
Closed addressing (open hashing)
The methods used include:
Linked list,
Binary tree…
Q.22 In RDBMS, what is the efficient data structure used in the internal storage
representation?
Ans B+ tree. Because in B+ tree, all the data is stored only in leaf nodes, that
makes searching easier. This corresponds to the records that shall be stored in
leaf nodes.
Q.23 Draw the B-tree of order 3 created by inserting the following data arriving
in sequence – 92 24 6 7 11 8 22 4 5 16 19 20 78
Ans
11 -
5 7 19 24
4 - 6 - 8 - 16 - 20 22 78 92
11 -
better one since the property of complete binary tree is maintained even after
operations like additions and deletions are done on it.
Q.26 Does the minimum spanning tree of a graph give the shortest distance
between any 2 specified nodes?
Ans No.Minimal spanning tree assures that the total weight of the tree is kept at its
minimum. But it doesn’t mean that the distance between any two nodes
involved in the minimum-spanning tree is minimum.
Q.27 Convert the given graph with weighted edges to minimal spanning tree.
Ans
600
1 3 200
612
410 310 5
2985
2 400
4
1421
the equivalent minimal spanning tree is:
1 3
200
410 612 310
2 4 5