Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
174 views

Advanced Data Structure Lab Programs

tree, heap sort, quick sort, insertion sort, red-black tree,traveling sales man problem, minimum spanning tree

Uploaded by

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

Advanced Data Structure Lab Programs

tree, heap sort, quick sort, insertion sort, red-black tree,traveling sales man problem, minimum spanning tree

Uploaded by

kajendran4958
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 84

1

Exp.No:- 01
Date:- 13.07.2014
INSERTION SORT

AIM:
To write a program in C to sort the given elements using Insertion sort technique

THEORY:
An insertion sort is one that sorts a set of records by inserting records into an existing
sorted file. The simple insertion sort can be viewed as a general selection sort in which
the priority queue is implemented as an ordered array. Processing is needed only for
insertion of elements. Once the elements have been inserted, they are already sorted, so
that no selection is necessary.
Procedure:
1. For pass = 1 to n 1
a) Index = pass
b) Place data[index] in correct position among data[0] . data[pass]
2. End.
Analysis:
1. Worst- Case Analysis = O(n
2
)
2. Best Case Analysis = O(n)
3. Average Case Analysis = O (N log N)

ALGORITHM:
1. Enter the number of elements to be sorted.
2. Enter the first element into the array.
3. The second element is compared with the elements that are already present in the
array.
4. After comparing it with each element place that element in the right position in
array.
5. Repeat steps 3 and 4 for every element that you are inserting into the array.
6. Terminate the process after sorting all the elements in the array.

2
PROGRAM:
#include<stdio.h>

void insertionsort(int x[],int n)
{
int i,p,elt;
for(p=1;p<n;p++)
{
i=p;
elt=x[i];
while((i>0)&&(x[i-1]>elt))
{
x[i]=x[i-1];
i--;
}
x[i]=elt;
}
}

void main()
{
int i,a[20],n;
printf("\n\tInsertion Sort");
printf("\nHow many Numbers:");
scanf("%d",&n);
printf("\nEnter the array elements:");
for(i=0;i<n;i++)
scanf("%d",&a[i]);
insertionsort(a,n);
printf("\nThe sorted list of elements are:");
for(i=0;i<n;i++)
printf(" %d",a[i]);
}

OUTPUT:
Insertion Sort
How many Numbers:5

Enter the array elements: 23 12 78 56 45

The sorted lists of elements are: 12 23 45 56 78

RESULT:
Thus, the program has been executed and output is verified.

3
Exp.No:- 02
Date:- 13.07.2014
QUICK SORT

AIM:
To write a program in C to sort the given elements using Quick sort technique.

THEORY:
Quick sort is based on the divide-and-conquer paradigm. It is a most efficient
internal sorting technique. Here is the three step based on the divide-and-conquer process
for sorting a typical sub array A [p.r].
1. DIVIDE:
The array A [p.r] portioned (rearranged) into two non-empty sub arrays
A [pq] and A [q+1r] such that A [pq] <= A [q+1r]. The index q is
computed as part of this partitioning procedure.
2. CONQUER:
The two sub array A [pq] and A [q+1r] are sorted by recursive
calls to quick sort.
3. COMBINE:
Since the sub array is sorted in place, no work is needed to combine them.
The entire array A [pq] is sorted.
Quick sort procedure is sorted by choosing a key value called Pivot element. This
Pivot element is used to rearrange element in the array. The pivot element may be the
first element or the last element in the array. Also it can be chosen randomly from
anywhere in the array. This type of sorting is called as Randomized Quick sort.

ANALYSIS:
1. Worst- Case Analysis = O (N
2
)
2. Best Case Analysis = O (N Log N)
3. Average Case Analysis = O (N log N)
ADVANTAGE:
1. It is faster than other O(N log N) algorithms.
2. It has better cache performance and high speed.

4
ALGORITHM:
1. Enter the number of elements to be sorted.
2. Initialize an index, low and high digits for a given array of elements.
3. Assign the element at the starting index to low
low a[0]
Assign the element at the last index to high
high a[n-1]
4. Assign the element at the index low to a variable key
key a[low]
5. Compare the lowest and highest element in array using index. Let i be the
lowest index and j be the highest index.
6. Exchange the elements until it satisfies the conditions below
If a[i]<=key and i<=j increment i
If a[j]>=key and j>=I decrement j
7. Repeat the above step until all the elements are sorted

PROGRAM:
#include<stdio.h>

void quicksort(int a[],int low, int high)
{
int i,j,pivot,temp;
if(low<high)
{
i=low+1;
j=high;
pivot = a[low];
while(i<=j)
{
while(pivot>=a[i])
i=i+1;
while(pivot<a[j])
j=j-1;
if(i<j)
{
temp = a[i];
a[i] = a[j];
a[j] = temp;

5
i=i+1;
j=j-1;
}
}
temp = a[low];
a[low]=a[j];
a[j]=temp;
quicksort(a,low,j-1);
quicksort(a,j+1,high);
}
}

void main()
{
int a[20],n,i;
printf("\n\t\tQUICK SORT");
printf("\nEnter the number of elements:");
scanf("%d",&n);
printf("\nEnter the elements:");
for(i=0;i<n;i++)
{
scanf("%d",&a[i]);
}
quicksort(a,0,n-1);
printf("\nThe Sorted List of Elements:");
for(i=0;i<n;i++)
{
printf(" %d",a[i]);
}
getch();
}

OUTPUT:
QUICK SORT
Enter the number of elements:9

Enter the elements: 20 -3 5 21 -30 12 56 2 19

The Sorted List of Elements: -30 -3 2 5 12 19 20 21 56


RESULT:
Thus, the program has been executed and output is verified.


6
Exp.No:- 03
Date:- 13.07.2014
HEAP SORT

AIM:
To write a program to sort the given array elements using the heap sort procedure.

THEORY:
The (binary) heap data structure is an array object that can be viewed as a
complete binary tree. Each node of the tree corresponds to an element of the array that
stores the value in the node.
The tree is completely filled on all levels except possibly the lowest, which is
filled from the left up to a point. An array A that represents a heap is an object with two
attributes: length [A], which is the number of element in the array, and heap-size [A], the
number of elements in the heap stored within the array A.
Heap sorting method has three procedures:
1. The HEAPIFY procedure.
2. The BUILD-HEAP procedure.
3. The HEAP SORT procedure.
The HEAPIFY procedure:
HEAPIFY is an important subroutine for manipulating heaps. Its input is an array
[A] and an index I into the array. When HEAPIFY is called, it is assumed that the binary
tree rooted at LEFT (i) and RIGHT (i) are heaps.
The key value in the parent node is smaller than or equal to the key value of any
of its child node.
The BUILD-HEAP procedure:
To build the heap, apply the heap order property starting from the right most non-
leaf node at the bottom level. The procedure BUILD-HEAP goes to the remaining node
into the tree and runs HEAPIFY n each one. The order in which the nodes are processed
guarantees that the sub-tree rooted at the children of the node I are heaps before
HEAPIFY is run at that node.

7
The HEAP SORT procedure:
The Heap sort algorithm starts by using BUILD-HEAP to build a heap on the
input array A [1n], where n = length [A]. Since the maximum element of the array is
stored at the root A[1], it can be put into the correct final position by exchanging it with
A[n], If we now discard node n from the heap the sorted elements are obtained. The
Heap order property is maintained each and every time the element is discarded from the
heap. Thu the sorted array elements are obtained.
Analysis:
1. The HEAPIFY procedure, which runs in O (log n) time, is the key to
maintain the heap property.
2. The BUILD-HEAP procedure, which runs in linear time, produces a heap
from an unordered input array.
3. The HEAP SORT, which run in O (n log n) time, sort an array in-place.
Advantages:
1. It is efficient for sorting large number of elements.
2. It has the advantages of Worst case O (n lg n) running time.
Limitations:
1. It is not a stable sort.
2. It requires more processing time.

ALGORIHTM:
1. Enter the array size and the elements to be sorted
2. Perform Build heap algorithm
3. for i length[a] down to 2
4. Do exchange
5. Decrement heapsize by 1
6. Call Heapify function
7. Print the sorted array
8. Stop the program
Procedure for Build heap(a) :
1. for i length[a]/2 down to 1

8
2. Call heapify function
Procedure for Heapify (a,i):
1. left child (l) = 2* parent position (i)
2. right child (r) = (2 * parent position(i) ) +1
3. if((a[ l ]>a[i]) && (l<=x))
4. then assign leftchild to largest
5. else assign parent to largest
6. if((a[r]>a[large]) && (r<=x)
7. then assign right child to largest
8. else assign parent and check if largest is not equal to right child
9. then a[ i ] a[large]
10. Call heapify ( a, large )

PROGRAM:
#include<stdio.h>
void heapify(int a[],int m)
{
int i,j,q,temp;
for(q=2;q<=m;q++)
{
i=q;
j=i/2;
temp=a[i];
while(j>=1 &&temp>a[j])
{
a[i] = a[j];
i=j;
j=j/2;
}
a[i]=temp;
}
}

void heap(int a[],int n)
{
int i,temp;
for(i=n;i>=2;i--)
{
heapify(a,i);

9
temp=a[1];
a[1]=a[i];
a[i]=temp;
}
}

void main()
{
int a[20],n,i;
printf("\n\t\tHEAP SORT");
printf("\nEnter the number of elements:");
scanf("%d",&n);
for(i=1;i<=n;i++)
{
printf("\nEnter the %d elements:",i+1);
scanf("%d",&a[i]);
}
heap(a,n);
printf("\nThe Sorted List of Elements:");
for(i=1;i<=n;i++)
{
printf(" %d",a[i]);
}
getch();
}

OUTPUT:
HEAP SORT
Enter the number of elements:6
Enter the 1 elements:23
Enter the 2 elements:56
Enter the 3 elements:12
Enter the 4 elements:89
Enter the 5 elements:67
Enter the 6 elements:5
The Sorted List of Elements: 5 12 23 56 67 89

RESULT:
Thus, the program has been executed and output is verified.







10
Exp.No:- 04
Date:- 13.07.2014
BUCKET SORT

AIM:
To write a program in C to sort the given elements using Bucket sort

THEORY:
Bucket sort, or bin sort, is a sorting algorithm that works by partitioning an array
into a number of buckets. Each bucket is then sorted individually, either using a different
sorting algorithm, or by recursively applying the bucket sorting algorithm. It is a
distribution sort, and is a cousin of radix sort in the most to least significant digit flavour.
Bucket sort is a generalization of pigeonhole sort. Bucket sort can be implemented with
comparisons and therefore can also be considered a comparison sort algorithm. The
computational complexity estimates involve the number of buckets.
Bucket sort is mainly useful when input is uniformly distributed over a range. For
example, consider the following problem.
Bucket sort works as follows:
bucketSort(arr[], n)
1) Create n empty buckets (Or lists).
2) Do following for every array element arr[i].
a) Insert arr[i] into bucket[n*array[i]]
3) Sort individual buckets using insertion sort.
4) Concatenate all sorted buckets.



11

Efficiency:
Worst case performance (n
2
)
Average case performance

Worst case space complexity


ALGORITHM:
1. Start
2. Enter the elements of the input array A.
3. n length [A]
4. For i = 1 to n do
5. Insert A[i] into list B[nA[i]]
6. For i = 0 to n-1 do
7. Sort list B with Insertion sort
8. Concatenate the lists B[0], B[1], . . B[n-1] together in order.
9. Stop
PROGRAM:

#include<stdio.h>
void insertionsort(int[],int);

void bucketsort(int a[],int n)
{
int i,j,k=0,bn,b[10][10]={0},count[10]={0};
for(i=0;i<n;i++)
{
bn=n*a[i]/1000;
b[bn][count[bn]++]=a[i];
}

12
for(i=0;i<n;i++)
if(count[i]!=0)
insertionsort(b[i],count[i]);
for(i=0;i<n;i++)
{
if(count[i]!=0)
{
for(j=0;j<count[i];j++)
a[k++]=b[i][j];
}
}
}

void insertionsort(int x[],int n)
{
int i,p,elt;
for(p=1;p<n;p++)
{
i=p;
elt=x[i];
while((i>0)&&(x[i-1]>elt))
{
x[i]=x[i-1];
i--;
}
x[i]=elt;
}
}

void main()
{
int i,a[20],n;
printf("\n\tBucket Sort");
printf("\nHow many Numbers:");
scanf("%d",&n);
printf("\nEnter the array elements:");
for(i=0;i<n;i++)
scanf("%d",&a[i]);
bucketsort(a,n);
printf("\nThe sorted list of elements are:");
for(i=0;i<n;i++)
printf(" %d",a[i]);
}




13
OUTPUT:
Bucket Sort
How many Numbers:7

Enter the array elements:34
23
12
89
-7
32
12

The sorted list of elements are: -7 12 12 23 32 34 89

RESULT:
Thus, the program has been executed and output is verified.
















14
Exp.No:- 05
Date:- 13.07.2014
POLYNOMIAL DIFFERENTIATION
AIM:
To create a C program to differentiate the given polynomial using linked list.

THEORY:
1. Input the polynomial f(x,y,z) to fx.
2. Multiply the coefficient with the exponent and subtract the exponent by 1
of the variable of each term which is differentiated with respect to that
variable.
3. Do until fx points to NULL;
4. fx will now be the first derivative of the polynomial with respect to the
that variable.
ALGORITHM:
1. Declare the structure for linked list node and pointers (*s,*t) to point the first
node of the given polynomial and the differentiated polynomial and their
pointers(*sp,*tp) to point the current position in source and destination
polynomial expression.
2. Get the co efficient for the powers in the expression with the
maximum exponent (max)entered by the user.
3. Create a new node temp and store the expression and the co efficient.
Assign temp->next as NULL
4. If *s is NULL then make *s to point temp and *sp to point the same node.
Else
Make *sp->next to point temp and then move sp to temp.
5. Repeat step 3 through step 4 for all powers in the expression.
6. Reassign *sp with *s ,to point the first node in the source polynomial.
7. While *sp is not NULL do the following
a. Set temp->co efficient to sp->coeff sp->exp
b. Set temp->exp to sp->exp-1;

15
c. Set temp->next to NULL;
d. If *t is NULL
Make *t and *tp to point temp
Else
Set tp->next = temp and move tp to temp.
8. Set *tp to point the first node in the differential polynomial.
9. For all the powers from max through 0 .
a. Print the co efficients and exponent.
b. Move *tp to next node.
a. int th
PROGRAM:

#include<stdio.h>
#include<conio.h>
void appendpoly(int,int);

struct nodetype
{
int c;
int e;
struct nodetype *link;
}*head=NULL,*res=NULL;

typedef struct nodetype node;

void createpoly()
{
int i,term,coeff,exp;
printf("\nEnter the number of polynomial terms:");
scanf("%d",&term);
for(i=0;i<term;i++)
{
printf("Enter the Co-efficient for %d term:",i+1);
scanf("%d",&coeff);
printf("Enter the Exponent:");
scanf("%d",&exp);
appendpoly(coeff,exp);
}
}

void appendpoly(int x,int y)
{
node *temp=(node*)malloc(sizeof(node));
temp->c=x;
temp->e=y;

16
temp->link=NULL;
if(head==NULL)
head=temp;
else
{
node *t=head;
while(t->link!=NULL)
t=t->link;
t->link=temp;
}
}

void diffpoly()
{
node *t=head,*t1,*temp;
while(t)
{
temp=(node*)malloc(sizeof(node));
temp->c=t->c*t->e;
temp->e=t->e-1;
temp->link=NULL;
if(res==NULL)
res=temp;
else
{
t1=res;
while(t1->link!=NULL)
t1=t1->link;
t1->link=temp;
}
t=t->link;
}
}

void displaypoly(node *first)
{
int f=0;
node *temp=first;
while(temp!=NULL)
{
if(f!=0)
{
if(temp->c!=0)
{
if(temp->c > 0)
printf("+");

17
if(temp->e> 0)
printf("%dX^%d",temp->c,temp->e);
else
printf("%d",temp->c);
}
}
else
{
if(temp->e>0)
printf("%dX^%d",temp->c,temp->e);
else
printf("%d",temp->c);
}
temp=temp->link;
f=1;
}
}
void main()
{
createpoly();
printf("\nThe given Polynomial is:\n");
displaypoly(head);
printf("\nThe differntiated Polynomail is:\n");
diffpoly();
displaypoly(res);
}

OUTPUT:
Enter the number of polynomial terms:4
Enter the Co-efficient for 1 term:3
Enter the Exponent:3
Enter the Co-efficient for 2 term:4
Enter the Exponent:2
Enter the Co-efficient for 3 term:1
Enter the Exponent:1
Enter the Co-efficient for 4 term:5
Enter the Exponent:0
The given Polynomial is: 3X^3+4X^2+1X^1+5
The differentiated Polynomial is: 9X^2+8X^1+1

RESULT:
Thus, the program has been executed and output is verified.



18
Exp.No:- 06
Date:- 03.08.2014
PRINTING NODES LEVELWISE

AIM:
To list all the nodes of a tree in level order, first list the root node then all
the nodes in level 1, level 2 and so on. Nodes at the same level are printed in left to right
order.

THEORY:
A tree is a finite set of elements or nodes. If the set is non-empty, one of the
nodes is distinguished as the root node, while the remaining (possibly empty) set of
nodes are grouped into subsets, each of which is itself a tree. This hierarchical
relationship is described by referring to each such sub-tree as a child of the root, while
the root is referred to as the parent of each sub-tree.
The level of a node is its distance from the root. Because the root has a zero
distance from itself, the root is at level 0. The children of the root are at the level 1.















ALGORITHM:
1. Start
2. Enter the number of nodes n to be inserted into the tree
3. Create a node for each value where each node has a data field, left child and
right child.
10
20 30
40 50 60
80 70
Figure: Level of the tree
Node at level 0
Node at level 1
(20, 30)
Node at level 2
(40, 50, 60)
Node at level 3
(70, 80)

19
4. Create a binary tree using the following procedure
a. Set the first value to the root node
b. Read the next value, if the next value is greater than the root, then
make it as the right node , else if it is lesser than the root make it as the
left node.
c. Repeat the above steps for all the nodes
5. Print all the values in level wise
6. Stop

PROGRAM:
#include<stdio.h>
#include<conio.h>

struct nodetype
{
int info;
struct nodetype *left,*right;
}*tree=NULL;
typedef struct nodetype *NODEPTR;
void printGivenLevel(NODEPTR root,int level);
int height(NODEPTR node);

void printLevelOrder(NODEPTR root)
{
int h=height(root);
int i;
for(i=1;i<=h;i++)
{
printf("\n Level:%d\n",i-1);
printGivenLevel(root,i);
}
}

void printGivenLevel(NODEPTR root,int level)
{
if(root==NULL)
return;
if(level==1)
printf("%d ",root->info);
else if(level > 1)
{
printGivenLevel(root->left,level-1);

20
printGivenLevel(root->right,level-1);
}
}

int height(NODEPTR node)
{
if(node==NULL)
return 0;
else
{
int lheight=height(node->left);
int rheight=height(node->right);
if(lheight > rheight)
return(lheight+1);
else return(rheight+1);
}
}

NODEPTR InsertBST(int elt,NODEPTR t)
{
if(t==NULL)
{
t=(NODEPTR) malloc(sizeof(struct nodetype));
if(t==NULL)
printf("No Memory error");
else
{
t->info=elt;
t->left=NULL;
t->right=NULL;
}
}
else if(elt<t->info)
t->left = InsertBST(elt,t->left);
else if(elt>t->info)
t->right= InsertBST(elt,t->right);
return t;

}

void main()
{
int a,i,n;
printf("Binary Search Tree Traversal");
printf("\nEnter the number of elements:");
scanf("%d",&n);

21
printf("Enter the elements:");
for(i=0;i<n;i++)
{
scanf("%d",&a);
tree=InsertBST(a,tree);
}
printf("\nLevel Order Traversal is:");
printLevelOrder(tree);
}

OUTPUT:
Enter the number of elements:7
Enter the elements:23
11
45
56
5
15
30

Level Order Traversal is:
Level:0
23
Level:1
11 45
Level:2
5 15 30 56


RESULT:
Thus, the program has been executed and output is verified.















22
Exp.No:- 07
Date:- 03.08.2014
BINARY SEARCH IN N * N MATRIX

AIM:
To write a C program to search a given n element in N * N matrix using binary
search algorithm

THEORY:
In an array implementation of sequential search we reduce the total search time
for a large set of items by using a search procedure based on applying the standard divide
and conquer method.
Divide and Conquer
Divide the items in to two parts and determine to which of the two parts the
search key belongs the cent rate on that part.
Binary search
Binary search uses only three operations to find a search key value in sample. On
first call the algorithm compares key value to the middle of the file. If key value is larger
than the key, next interaction involves the right half. Otherwise the iteration process for
left half. After one more interaction the algorithm finds the search key value.

ALGORITHM:

1. Get the order of the matrix (N*N) and the elements of the matrix.
2. Check whether the elements of the matrix entered are in ascending order. If
not sort the given element.
3. Get the element to be searched(x).
4. Set a loop I ranging from 0 to n-1.
5. Assign low=0 , high =n
6. While low<=high
i. Find mid =(low + high)/2

23
ii. If x=a[i][mid] then set flag = true and print the position of the
element(i+1,mid+1)
iii. If x>a[i][mid] then search in the right side of mid by incrementing
low as mid+1
iv. If x<a[i][mid] then search in the left side of mid by decrementing
high as mid-1
7. If flag is not set print the element is not found in the array.

PROGRAM:

#include<stdio.h>
#include<conio.h>

int matrix[10][10],i,j;

void search(int n,int num)
{
for(i=0;i<n;i++)
{
int low=0,high=n-1,mid;
for(mid=(low+high)/2;low<=high;mid=(low+high)/2)
{
if(matrix[i][mid]==num)
{
printf("\nThe Number %d is at position %d %d",num,i+1,mid+1);
return;
}
else
if(matrix[i][mid]<num)
low=mid+1;
else
high=mid - 1;
}
}
printf("\nThe number %d is not present",num);
}

void insertionsort(int x[],int n)
{
int i,p,elt;
for(p=1;p<n;p++)
{

24
i=p;
elt=x[i];
while((i>0)&&(x[i-1]>elt))
{
x[i]=x[i-1];
i--;
}
x[i]=elt;
}
}

void matrixsort(int x[][10],int n)
{
int i,j,k=-1,l=-1;
int a[20];
for(i=0;i<n;i++)
for(j=0;j<n;j++)
a[++k]=x[i][j];
insertionsort(a,k+1);
for(i=0;i<n;i++)
for(j=0;j<n;j++)
x[i][j]=a[++l];
}

void main()
{
int n,num;
printf("\nEnter the order of Matrix:");
scanf("%d",&n);
printf("\nEnter the Matrix elements:");
for(i=0;i<n;i++)
for(j=0;j<n;j++)
scanf("%d",&matrix[i][j]);
matrixsort(matrix,n);
printf("\nThe given Sorted Matrix is:\n");
for(i=0;i<n;i++)
{
for(j=0;j<n;j++)
printf(" %d",matrix[i][j]);
printf("\n");
}
printf("\nEnter the number to be searched:");
scanf("%d",&num);
search(n,num);
}


25
OUTPUT:

Enter the order of Matrix:3

Enter the Matrix elements:12
56
34
23
89
78
55
44
33

The given Sorted Matrix is:
12 23 33
34 44 55
56 78 89

Enter the number to be searched: 78

The Number 78 is at position 3 2


RESULT:
Thus, the program has been executed and output is verified.















26
Exp.No:- 08
Date:- 03.08.2014
BINARY TREE TRAVERSAL

AIM:
To create a binary tree and traverse in In-order and Post-order, Pre-order.

THEORY:
A binary tree traversal requires that each node of the tree be processed only
once in a predetermined sequence. There are basically three traversal methods for binary
tree. They are,
1. In-order Traversal
2. Pre-order Traversal
3. Post-order Traversal

1. In-order Traversal: (or symmetric order traversal)
To traverse a nonempty binary tree in in-order, we perform the following three
operations:
1. Traverse left subtree in in-order
2. Visit the root
3. Traverse the right subtree in in-order
It is also called as symmetric order traversal. The figure illustrates the binary tree and its
in-order traversal (shown in dotted line).









Inorder : C B D A F E G

Figure. Inorder Traversal

A
B
E
C D G
F


27
2. Preorder Traversal: (or Depth first order traversal)
To traverse a nonempty binary tree in preorder, we perform the following three
operations:
1. Visit the root.
2. Traverse the left subtree in preorder.
3. Traverse the right subtree in preorder.
It is also known as depth first order traversal. The figure illustrates the binary tree and
their preorder traversal (shown in dotted line).












3. Postorder Traversal
To traverse a nonempty binary tree in postorder, we perform the following three
operations:
1. Traverse the left subtree in postorder
2. Traverse the right subtree in postorder
3. Visit the root.
The figure illustrates the binary tree and their postorder traversal (shown in dotted line).




Preorder : A B C D E F G
Figure Preorder Traversal

A
B
E
C D G
F


28










ALGORITHM:

1. Start
2. Read the values of all nodes
3. Procedure for constructing binary tree:
i) Assume the first value as the root node
ii) If the second value is lesser than the root node value
make it the left child else make it the right child
iii) Repeat steps i and ii for all the input values
4. Procedure for preorder traversal:
i) Process the root node
ii) Process the left subtree
iii) Process the right subtree
5. Procedure for inorder traversal:
i) Process the left subtree
ii) Process the root node
iii) Process the right subtree
6. Procedure for postorder traversal:
i) Process the left subtree
ii) Process the right subtree
iii) Process the root node
7. Stop
A
B
E
C D G
F

Postorder : C D B F G E A

Figure Postorder Traversal


29
PROGRAM:

#include<stdio.h>
#include<conio.h>

struct nodetype
{
int info;
struct nodetype *left,*right;
}*tree=NULL;
typedef struct nodetype *NODEPTR;

NODEPTR InsertBST(int elt,NODEPTR t)
{
if(t==NULL)
{
t=(NODEPTR) malloc(sizeof(struct nodetype));
if(t==NULL)
printf("No Memory error");
else
{
t->info=elt;
t->left=NULL;
t->right=NULL;
}
}
else if(elt<t->info)
t->left = InsertBST(elt,t->left);
else if(elt>t->info)
t->right= InsertBST(elt,t->right);
return t;
}

void intrav(NODEPTR tree)
{
if(tree!=NULL)
{
intrav(tree->left);
printf("%d\t",tree->info);
intrav(tree->right);
}
}
void pretrav(NODEPTR tree)
{
if(tree!=NULL)
{

30
printf("%d\t",tree->info);
pretrav(tree->left);
pretrav(tree->right);
}
}
void posttrav(NODEPTR tree)
{
if(tree!=NULL)
{
posttrav(tree->left);
posttrav(tree->right);
printf("%d\t",tree->info);
}
}

void main()
{
int a,i,n;
printf("Binary Tree Traversal");
printf("\nEnter the number of elements:");
scanf("%d",&n);
printf("Enter the elements:");
for(i=0;i<n;i++)
{
scanf("%d",&a);
tree=InsertBST(a,tree);
}
printf("\nIn-Order Traversal is:");
intrav(tree);
printf("\nPre-Order Traversal is:");
pretrav(tree);
printf("\nPost-Order Traversal is:");
posttrav(tree);
getch();
}

OUTPUT:
BINARY TREE TRAVERSAL
Enter the number of elements: 7
Enter the elements: 25 15 35 45 10 5 50
In-Order Traversal is: 5 10 15 25 35 45 50
Pre-Order Traversal is: 25 15 10 5 35 45 50
Post-Order Traversal is: 5 10 15 50 45 35 25

RESULT:
Thus, the program has been executed and output is verified.

31
Exp.No:- 09
Date:- 03.08.2014
IMPLEMENTING RED BLACK TREE

AIM:
To implement insertion, search operation in RED BLACK tree using high
level language.

THEORY:
A Read Black tree is a binary search tree with one extra bit of storage per node. It
is a color which can be either RED or BLACK.
The nodes can be colored on any path from root to a left, RED BLACK tree
ensures that no such path is more than twice as long as any other, so it is approximately
balanced.
Each node of the tree contains the fields, color, key, left, right and p. If a child or
a parent of a node does not exists the corresponding pointes field of the node contains
NIL value.
A binary search tree is a RED-BLACK tree, it satisfies the following properties.
PROPERTIES OF RED BLACK TREE:
1. Every node is either red or black
2. Every left is black
3. If a node is Red, then both its children are BLACK
4. Every simple path of node to a descendant leaf contains the same number of
BLACK nodes.
The dynamic set of operations like SEARCH, MINIMUM, MAXIMUM,
SUCCESSOR and PREDECESSOR can be implemented on RED BLACK TREE. We
can also perform insertion and deletion operation but they do not support direct the
property will not be obtained so we have to change the color.
ROTATION:
While we are inserting or deleting the node the properties does not restore so we
have to change the color of node and also the pointer structure. The pointer stricture can
be changed through rotation.

32
LEFT ROTATION:
If we are performing left rotation operation on X whose right child is Y and it is
not NIL. The left rotation pivots around the link from X to Y. It makes Y the new root of
that sub tree with X and Ys left child and Ys left child as Xs right child.
RIGHT ROTATION:
If we are performing right rotation operation on X whose left child is Y and it is
not NIL. The right rotation pivots around the link from X to Y. It makes Y the new root
of that sub tree with X and Ys right child and Ys right child as Xs left child.
INSERTION:
Using insert procedure we can insert the nodes in a binary search tree and we
color X as RED we can change the color to obtain the property.
Inserting in Red-Black Tree

Color the node Red
Insert as in a regular BST
If have parent is red

Case 1


x is node of interest, x's uncle is Red



33


Decrease x's black height by one
Case 2

x's uncle is Black, x is a Right child



Transform to case 3
Case 3

x's uncle is Black, x is a Left child


Terminal case, tree is Red-Black tree
Insertion takes O(lg(n)) time.Requires at most two rotations




34
ALGORITHM:
Procedure for Left rotation :
1. Assume node x is the parent and node y is a non-leaf left child.
2. Let y be the parent and x be its right child.
3. Let ys right child be xs left child.

Procedure for Right rotation:
1. Assume node x is the parent and node y is a non-leaf right child.
2. Let y be the parent and x be its left child.
3. Let ys left child be xs right child.

Procedure for Insertion:
1. Start
2. Insert the node x in the tree T with the normal procedue
To restore the red-black property
3. x->colour = red;
4. while ( (x != T->root) && (x->parent->colour == red) ) then do from
step 5 to step 16 else repeat step 5 to step 16 with the "if" part with right
and left exchanged
5. if ( x->parent == x->parent->parent->left ) then do from step 6
6. If x's parent is a left, y is x's right 'uncle' then y = x->parent->parent-
>right;
7. If ( y->colour == red ) then do step 8 to step 11 else goto step 12.
/* case 1 - change the colours */
8. x->parent->colour = black;
9. y->colour = black;
10.x->parent->parent->colour = red;
11.x = x->parent->parent. (Move x up the tree)
/* y is a black node */
12. if ( x == x->parent->right ) then do from step 13
/* and x is to the right */

35
/* case 2 - move x up and rotate */
13.x = x->parent and left rotate about x.
/* case 3 */
14. x->parent->colour = black;
15.x->parent->parent->colour = red;
16.right_rotate( T, x->parent->parent );
17.T->root->colour = black; /* Colour the root black */
18. Stop

PROGRAM:

#include<stdio.h>
#include<conio.h>
struct nodetype
{
char color;
int key;
struct nodetype *left,*right,*p;
}*root,*nil;
typedef struct nodetype node;
int level;

void rb_tree()
{
nil=(node*)malloc(sizeof(node));
nil->p=nil->left=nil->right=nil;
nil->color='b';
root=nil;
level=0;
}

void left_rotate(node *x)
{
node *y;
y=x->right;
x->right=y->left;
if(y->left!=nil)
(y->left)->p=x;
y->p=x->p;
if(x->p==nil)
root=y;
else if(x==(x->p)->left)

36
(x->p)->left=y;
else
(x->p)->right=y;
y->left=x;
x->p=y;
}
void right_rotate(node *x)
{
node *y;
y=x->left;
x->left=y->right;
if(y->right!=nil)
(y->right)->p=x;
y->p=x->p;
if(x->p==nil)
root=y;
else if(x==(x->p)->right)
(x->p)->right=y;
else
(x->p)->left=y;
y->right=x;
x->p=y;
}

void tree_insert(node *z)
{
node *y,*x;
y=nil;
x=root;
while(x!=nil)
{
y=x;
if(z->key<x->key)
x=x->left;
else
x=x->right;
z->p=y;
}
if(y==nil)
root=z;
else if(z->key<y->key)
y->left=z;
else
y->right=z;
}


37
void rb_insert()
{
node *x,*y;
x=(node*)malloc(sizeof(node));
printf("\nEnter he value of the node:");
scanf("%d",&x->key);
x->p=x->left=x->right=nil;
tree_insert(x);
x->color='r';
while(x!=root && (x->p)->color == 'r')
{
if(x->p==((x->p)->p->left))
{
y=((x->p)->p)->right;
if(y->color=='r')
{
(x->p)->color='b';
y->color='b';
((x->p)->p)->color='r';
x=(x->p)->p;
}
else if(x==(x->p)->right)
{
x=x->p;
left_rotate(x);
}
else
{
(x->p)->color='b';
((x->p)->p)->color='r';
right_rotate((x->p)->p);
}
}
else
{
y=((x->p)->p)->left;
if(y->color=='r')
{
(x->p)->color='b';
y->color='b';
((x->p)->p)->color='r';
x=(x->p)->p;
}
else if(x==(x->p)->left)
{
x=x->p;

38
left_rotate(x);
}
else
{
(x->p)->color='b';
((x->p)->p)->color='r';
right_rotate((x->p)->p);
}
}
}
root->color='b';
}

void inorder(node *x, int i)
{
if(x!=nil)
{
i++;
if(level<i)
level=i;
inorder(x->left,i);
printf("%c - %d - %d\n",x->color,x->key,i);
inorder(x->right,i);
}
}

void rb_display()
{
inorder(root,-1);
printf("\nTotal number of levels:%d\n",level+1);
}

void main()
{
int op;
printf(\nRED-BLACK TREE);
rb_tree();
printf("\n1.INSERT\n2.DISPLAY-INORDER\n3.EXIT");
do
{
printf("\nEnter your choice:");
scanf("%d",&op);
switch(op)
{
case 1:rb_insert();break;
case 2:rb_display();break;

39
case 3:exit(0);
default:printf("Invalid Option");break;
}
}while(op!=3);
}


OUTPUT:
RED-BLACK TREE
1. Insert
2.Display - Inorder
3.Exit
Enter your choice:1
Enter the value of the node: 43
Enter your choice:1
Enter the value of the node: 41
Enter your choice:1
Enter the value of the node: 38
Enter your choice:1
Enter the value of the node: 31
Enter your choice:1
Enter the value of the node: 12
Enter your choice:1
Enter the value of the node: 19
Enter your choice:1
Enter the value of the node: 8
Enter your choice: 2
r - 8 - 3
b - 12 - 2
r - 19 - 3
r - 31 - 1
b - 38 - 2
b - 41 - 0
b - 43 - 1
Total number of levels: 4
Enter your choice: 3

RESULT:
Thus, the program has been executed and output is verified.








40
Exp.No:- 10
Date:- 03.08.2014

KNAPSACK PROBLEM
AIM:
To find a solution vector for the knapsack problem using greedy method

THEORY:
The knapsack problem is a problem in combinatorial optimization. It derives its
name from the maximization problem of choosing possible essentials that can fit into one
bag (of maximum weight) to be carried on a trip. Given a set of items, each with a cost
and a value, then determine the number of each item to include in a collection so that the
total cost is less than some given cost and the total value is as large as possible.
In the following, we have n kinds of items, 1 through n. Each item j has a value pj
and a weight wj. The maximum weight that we can carry in the bag is c. The knapsack
problem restricts the number of each item to a specific value.
Mathematically the bounded knapsack problem can be formulated as:
maximize
subject to
The unbounded knapsack problem places no bounds on the number of each item.
The Fractional Knapsack Problem Given:
A set S of n items, with each item i having
bi - a positive benefit
wi - a positive weight
Goal: Choose items with maximum total benefit but with weight at most W.
If we are allowed to take fractional amounts, then this is the fractional knapsack problem.
In this case, we let xi denote the amount we take of item i
Objective: maximize

S i
i i i
w x b ) / (


41
Constraint:


S i
i
W x

Given n items of known weights w
1
,w
2
,,w
n
and values v
1
,v
2
,v
n
and a
knapsack of capacity W, we need to find the most valuable subset of the items that fit into
the knapsack. All weights and the knapsacks capacity are positive integers.
Step 1. Compute the value-to-weight ratios v
i
/w
i
, i=1,2,n, for the item given.
Step 2. Sort the items in non increasing order of the ratios computed in Step 1.
(Ties can be broken arbitrarily.)
Step 3. Repeat the following operation until the knapsack is filled to its full
capacity or no item is left in the sorted list: if the current item on the list fits into the
knapsack in its entirety, take it and proceed to the next item; otherwise, take its largest
fraction to fill the knapsack to its full capacity and stop.

ALGORITHM:

1. Start
2. Read the number of objects n to be inserted into the knapsack
3. Read the size of the knapsack
4. Read the weights and profits of each object into the w and p arrays
5. Calculate the power of each object which is the ratio of its profit and its weight
6. Insert the object into the knapsack using the following greedy method
i) Arrange all the objects in the increasing order of their power ratio
ii) Calculate the percentage of the objects that can be included into the
knapsack using the following steps
Do for n items
i. Check if w[i] >0 then goto step 7, w is the weight of the knapsack
ii. Let x[i]=1 where x is the solution vector
iii. Let u=v-w[i]
iii) Check if i<n then x[i]=u/w[i]
7. Calculate the maximum profit of the knapsack which is the sum of each object
and the product of the solution vector and its profit



42
PROGRAM:
#include<stdio.h>
#include<conio.h>
#define MAX 10

int n,m,t[MAX];
float w[MAX],p[MAX],x[MAX],maxprofit;

void read()
{
int i;
printf("\nEnter the number of items:");
scanf("%d",&n);
printf("\nEnter the Knapsack Capacity:");
scanf("%d",&m);
for(i=1;i<=n;i++)
{
printf("\nEnter %d item Profit:",i);
scanf("%f",&p[i]);
printf("\nEnter its weight:");
scanf("%f",&w[i]);
x[i]=0.0;
}
}

void sort()
{
int i,j,temp;
for(i=1;i<=n;i++)
t[i]=i;
for(i=1;i<n;i++)
for(j=1;j<=n-i;j++)
if(p[t[j]]/w[t[j]] < p[t[j+1]] / w[t[j+1]])
{
temp=t[j];
t[j]=t[j+1];
t[j+1]=temp;
}
}

void greedyknap()
{
int i;
maxprofit=0;
sort();
for(i=1;i<=n;i++)

43
{
if(w[t[i]]>m)
break;
x[t[i]]=1.0;
m=m-w[t[i]];
maxprofit +=p[t[i]];
}
if(i<=n)
{
x[t[i]] = (float) m / w[t[i]];
maxprofit +=x[t[i]] * p[t[i]];
}
}

void main()
{
int i;
printf("\n GREEDY KNAPSACK PROBLEM");
read();
greedyknap();
printf("\nThe Optimal Solution is: %f",maxprofit);
printf("\nThe Solution Vector is:\n");
for(i=1;i<=n;i++)
printf("\t%f",x[i]);
}

OUTPUT:
GREEDY KNAPSACK PROBLEM
Enter the number of items:4
Enter the Knapsack Capacity:6
Enter 1 item Profit:20
Enter its weight:3
Enter 2 item Profit:40
Enter its weight:2
Enter 3 item Profit:20
Enter its weight:5
Enter 4 item Profit:34
Enter its weight:1
The Optimal Solution is: 94.000000
The Solution Vector is:
1.000000 1.000000 0.000000 1.000000

RESULT:
Thus, the program has been executed and output is verified.

44
Exp.No:- 11
Date :- 23.08.2014

TRAVELLING SALESMAN PROBLEM

AIM:
To write a program to find the solution for the Traveling Salesman Problem using
Nearest Neighbour Algorithm

THEORY:
The traveling salesman problem (TSP) asks for the shortest route to visit a
collection of cities and return to the starting point. Given a collection of cities and the
cost of travel between each pair of them, the traveling salesman problem, or TSP for
short, is to find the cheapest way of visiting all of the cities and returning to your starting
point. The Travelling Salesman Problem (TSP) is a deceptively simple combinatorial
problem. It can be stated very simply:
A salesman spends his time visiting n cities (or nodes) cyclically. In one tour he
visits each city just once, and finishes up where he started. Many TSP's are symmetric -
that is, for any two cities A and B, the distance from A to B is the same as that from B to
A. In this case you will get exactly the same tour length if you reverse the order in which
they are visited - so there is no need to distinguish between a tour and its reverse, and you
can leave off the arrows on the tour diagram. If there are only 2 cities then the problem is
trivial, since only one tour is possible. For the symmetric case a 3 city TSP is also trivial.
If all links are present then there are (n-1)! different tours for an n city asymmetric TSP.
To see why this is so, pick any city as the first - then there are n-1 choices for the second
city visited, n-2 choices for the third, and so on. For the symmetric case there are half as
many distinct solutions - (n-1)!/2 for an n city TSP. In either case the number of solutions
becomes extremely large for large n, so that an exhaustive search is impractible.
ALGORITHM:
STEP 1: Start the Program

45
STEP 2: Get the Vertices and Edges with weight values for the every edge
Number of cities n and array of costs c(i,j) i,j=1,..n (We begin from
city number). Output: Vector of cities and total cost
STEP 3: Starting from first node
Starting values: C=0, cost=0, visits=0, e=1 (e=pointer of the visited city)

STEP 4: Go to the nearest unvisited vertex and Calculated the Cost
for r=1 to n-1 do
choose of pointer j with
minimum=c(e,j)=min{c(e,k);visits(k)=0 and k=1,..,n}
cost=cost+minimum
e=j
C(r)=j
end for loop

STEP 5: Repeat step 4 until all cities have been visited
STEP 6: Go to the starting city
C(n)=1 ,cost=cost+c(e,1)
STEP 7: Print the path of the tour and cost of the tour
STEP 8: Stop

PROGRAM:
#include<stdio.h>
#include<conio.h>

int a[10][10],visited[10],n,cost=0;

void mincost(int city)
{
int i,ncity;
visited[city]=1;
printf("%d---",city);
ncity = least(city);
if (ncity == 999)
{
ncity = 1;
printf("%d",ncity);
cost += a[city][ncity];
return;
}

46
mincost(ncity);
}

int least(int c)
{
int i,nc=999;
int min=999,kmin;
for(i=1;i<=n;i++)
{
if ((a[c][i] != 0) && (visited[i] == 0))
if (a[c][i] < min)
{
min = a[c][i] + a[i][1] ;
kmin = a[c][i];
nc = i;
}
}
if(min != 999)
cost += kmin;
return nc;
}

void main()
{
int i,j;
clrscr();
printf(\n\tTraveling Salesman Problem);
printf("\nEnter no.of cities: ");
scanf("%d",&n);
printf("\nEnter cost matrix: \n");
for(i=1;i<=n;i++)
{
for(j=1;j<=n;j++)
scanf("%d",&a[i][j]);
visited[i] = 0;
}
printf("\n\nThe Path is:\n\n");
mincost(1);
printf("\n\nMinimum cost:%d",cost);
getch();
}





47
OUTPUT:
Traveling Salesman Problem
Enter no.of cities: 4

Enter cost matrix:
0 1 3 6
1 0 2 3
3 2 0 1
6 3 1 0


The Path is:

1---2---4---3---1

Minimum cost: 8


RESULT:
Thus, the program has been executed and output is verified.















48
Exp.NO:- 12
DATE:- 23.08.2014
MINIMUM SPANNING TREE USING
KRUSKAL ALGORITHM

AIM:
To write a program to construct the minimum Spanning tree using Kruskals
Algorithm

THEORY:
A spanning tree of a graph G is a tree (V, E) where v is the vertices of G and E
is the subset of edges E of graph that connects all vertices as a tree.
A minimum spanning tree is a spanning tree in which the sum of the weight of the
edges is minimum.
In kruskal's algorithm, each vertex of a graph is taken as a one-node tree and a
forest of such V tree is created. Then a minimum weighted edge is selected to connect
two trees together. The iterations continue till all trees of the forest form a single tree.
An edge can be selected for inclusion if the following conditions are satisfied.
i) The inclusion of the edge should not form any circle.
ii) The cost of the resulting tree is minimum.
EXAMPLE:


49




ALGORITHM:

DISJOINT-SETS DATA STRUCTURE
Make_Set (v)
Create a new set whose only member is pointed to by v. Note that for this
operation v must already be in a set.

50
FIND_Set
Returns a pointer to the set containing v.
UNION (u, v)
Unites the dynamic sets that contain u and v into a new set that is union of these
two sets.
PROCEDURE FOR MST_KRUSKAL (G, w)
1. Start
2. A {} // A will ultimately contains the edges of the MST
3. for each vertex v in V[G]
4. do Make_Set (v)
5. Sort edge of E by nondecreasing weights w
6. for each edge (u, v) in E
7. do if FIND_SET (u) FIND_SET (v)
8. then A = AU{(u, v)}
9. UNION (u, v)
10. Return A
11. Stop

PROGRAM:

#include<stdio.h>
#include<conio.h>
struct vertex
{
int label;
};
struct edge
{
struct vertex v1,v2;
int w;
};
struct set
{
struct vertex v[10];
int label;
int count;
int alive;
};
struct set s[10];
//void join(struct set *s1,struct set *s2);

struct set findset(struct vertex v)
{
struct set st;

51
int i,j;
// printf("\n Findset");
//printf("%d",v.label);
for(i=1;i<=10;i++)
{
if(s[i].alive==1)
{
// printf("\n IN set %d",s[i].label);
for(j=1;j<=s[i].count;j++)
{
// printf(" %d",s[i].v[j].label);
if(s[i].v[j].label==v.label)
return s[i];
}
}
}
return st;
}

void join(struct set *s1,struct set *s2)
{
int i,j;
for(i=s1->count+1,j=1;j<=s2->count;i++,j++)
s1->v[i]=s2->v[j];
s1->count+=s2->count;
s2->alive=0;
s2->count=0;
}

void main()
{
struct vertex v[10];
struct edge e[20];
int ecount,cost=0;
int i,j,nv,ne;

clrscr();
printf("\n\tkruskal algorithm\n");
printf("\n Number of vertices:");
scanf("%d",&nv);

for(i=1;i<=nv;i++)
{
v[i].label=i;
s[i].v[1]=v[i];
s[i].count=1;

52
s[i].alive=1;
s[i].label=i;
}
printf("\n Number of edges:");
scanf("%d",&ne);
for(i=1;i<=ne;i++)
{
printf("Enter the vertices and weight of the edge:");
scanf("%d%d%d",&e[i].v1.label,&e[i].v2.label,&e[i].w);
}
for(i=1;i<ne;i++)
for(j=i+1;j<=ne;j++)
if(e[i].w>e[j].w)
{
struct edge temp =e[i];
e[i] = e[j];
e[j]=temp;
}
ecount=0;
/*for(i=1;i<=nv;i++)
{
printf("S%d",i);
for(j=1;j<=s[i].count;j++)
printf("%d ",s[i].v[j].label);
}*/
printf("\nMinimum Spanning Tree edges are:");
for(i=1;i<ne;i++)
{
struct set s1=findset(e[i].v1);
struct set s2=findset(e[i].v2);
if(s1.label!=s2.label)
{
printf(" %d->%d",e[i].v1.label,e[i].v2.label);
cost+=e[i].w;
ecount++;
join(&s[s1.label],&s[s2.label]);
}
}
if(ecount ==nv-1)
{
printf("\nThe cost of the Minimum spanning tree is: %d",cost);
printf("\n Finished");
getch();
}
}


53
OUTPUT:

KRUSKAL ALGORITHM

Number of vertices:4

Number of edges:5
Enter the vertices and weight of the edge:1 2 2
Enter the vertices and weight of the edge:1 3 4
Enter the vertices and weight of the edge:2 3 3
Enter the vertices and weight of the edge:2 4 4
Enter the vertices and weight of the edge:3 4 1

Minimum Spanning Tree edges are: 3->4 1->2 2->3
The cost of the Minimum spanning tree is: 6
Finished

RESULT:
Thus, the program has been executed and output is verified.





















54
Exp.No:- 13
DATE:- 23.08.2014

FLOYD WARSHALL ALGORITHM

AIM:
To find the shortest path using the Floyd Warshall Algorithm in C language

THEORY:
The Floyd-Warshall Algorithm is an efficient algorithm to find all-pairs shortest
paths on a graph. That is, it is guaranteed to find the shortest path between every pair of
vertices in a graph.
We examine the shortest path between the vertices u and v, by including other
vertices of the graph one by one and updating the distance with the minimum weight.
1. Initially path_wt[i] [j] = wt[i] [j] can be obtained from adjacency matrix.
2. path_wt[i] [j] = 0 if i = j (i.e., No cycle on same vertex)
3. Then a vertex k is included in the path between i and j. If the weight of the path
is less than that of the earlier weight, then path_ wt[i] [j] is updated.
4. The step 3 is repeated for all vertices (other than i and j) of the graph.
path_wt[i] [j] = min (path_wt[i] [j], path_wt[i] [k] + path_wt[k] [j]) for all k v
The following graph and its adjacency matrix illustrate the all pair shortest path
algorithm.


55
Step 1: Path matrix = weight matrix
0 1 2 3 4 5
0 0 8 4
1 0 6
2 4 0 3 5 4
3 3 5 0 4
4 6 3 0 2
5 6 0
Step 2: Including vertex 1 in the path of i, and j
0 1 2 3 4 5
0 0 8 14 4
1 0 6
2 4 0 3 5 4
3 3 5 0 4
4 6 3 0 2
5 6 0
Step 3:Including vertex 2 in the path i j
0 1 2 3 4 5
0 0 8 14 4 19 18
1 0 6 9 11 10
2 4 0 3 5 4
3 3 5 0 4 9
4 6 3 0 2
5 10 6 9 11 0
Step 4: Including vertex 3 in path i j
0 1 2 3 4 5
0 0 7 9 4 8 13
1 0 6 9 11 10
2 4 0 3 5 4

56
3 3 5 0 4 9
4 6 6 8 3 0 2
5 10 6 9 11 0
Step 5: Including vertex 4 in the path i j
0 1 2 3 4 5
0 0 7 9 4 8 10
1 17 0 6 9 11 10
2 11 4 0 3 5 4
3 10 3 5 0 4 6
4 6 6 8 3 0 2
5 17 10 6 9 11 0
Step 6: Including vertex 5 in path i j
0 1 2 3 4 5
0 0 7 9 4 8 10
1 17 0 6 9 11 10
2 11 4 0 3 5 4
3 10 3 5 0 4 6
4 6 6 8 3 0 2
5 17 10 6 9 11 0
Efficiency:
Time complexity of all pairs shortest path is O (n
3
)
ALGORITHM:
1. Start
2. Enter the total number of nodes and enter the elements
3. Enter the distance matrix into N x N matrix
4. The solution for all pair shortest path from vertex i to j with all intermediate
vertices in the subset { 1,2,k } when k = 0 path from vertex i to j with no
intermediate at all then it has almost one edge and hence dij(k) = w{ i,j }
5. The matrices Dn gives the final answer dij(n).s( i,j) for all i,j v

57
6. The matrix can be calculated for D. It can be calculated online just as the
value of matrix D
(k)
is computed. The recursive formula for ij(k) can be given.
7. Thus we find the shortest path of a node of every other node for the given graph.

PROGRAM:

#include<stdio.h>
#include<conio.h>
#include<stdlib.h>

void main()
{
int a[10][10],v,i,j,n,m,k,s=0;
clrscr();
printf("\n\tFLOYDS WARSHALL ALGORITHM");
printf("\nEnter the no. of vertices");
scanf("%d",&v);
printf("\nEnter the distance Matrix:");
for(i=1;i<=v;i++)
for(j=1;j<=v;j++)
scanf("%d",&a[i][j]);

for(i=1;i<=v;i++)
{
for(j=1;j<=v;j++)
{
for(k=1;k<=v;k++)
{
if(j!=k)
{
s=a[j][i]+a[i][k];
if((s < a[j][k]) || a[i][k]==0)
a[j][k]=s;
}
}
}
}
printf("\nAll Pair Shortest Path Graph Matrix is:\n");
for(m=1;m<=v;m++)
{
for(n=1;n<=v;n++)
printf("%d\t",a[m][n]);
printf("\n");
}
getch();

58
}

OUTPUT:
FLOYDS WARSHALL ALGORITHM

Enter the no. of vertices: 6

Enter the distance Matrix:
0 8 99 4 99 99
99 0 6 99 99 99
99 4 0 3 5 4
99 3 5 0 4 99
6 99 99 3 0 2
99 99 6 99 99 0

All Pair Shortest Path Graph Matrix is:
0 7 9 4 8 10
17 0 6 9 11 10
11 4 0 3 5 4
10 3 5 0 4 6
6 6 8 3 0 2
17 10 6 9 11 0

RESULT:
Thus, the program has been executed and output is verified.











59
Exp.No:- 14
DATE:- 23.08.2014

IMPLEMEMTING OCT TREES

AIM:
To write a program to implement Oct tree

THEORY:
An octree is a tree data structure in which each internal node has exactly
eight children. Octrees are most often used to partition a three dimensional space by
recursively subdividing it into eight octants. Octrees are the three-dimensional analog
of quadtrees. The name is formed from oct + tree, but note that it is normally written
"octree" with only one "t". Octrees are often used in 3D graphics and 3D game engines.

Each node in an octree subdivides the space it represents into eight octants. In a
point region (PR) octree, the node stores an explicit 3-dimensional point, which is the
"center" of the subdivision for that node; the point defines one of the corners for each of

60
the eight children. In a matrix based (MX) octree, the subdivision point is implicitly the
center of the space the node represents. The root node of a PR octree can represent
infinite space; the root node of an MX octree must represent a finite bounded space so
that the implicit centers are well-defined. Note that Octrees are not the same as k-d
trees: k-d trees split along a dimension and octrees split around a point. Also k-d trees are
always binary, which is not the case for octrees. By using adepth-first search the nodes
are to be traversed and only required surfaces are to be viewed.
ALGORITHM:

1. Start
2. Sequentially read in the image
3. Every color is then stored in an octree of depth 8 (every leaf at depth 8
represents a distinct color).
4. If there are less than K leaves the color is filtered down the tree until either it
reaches some leaf node that has an associated representative color or it
reaches the leaf node representing its unique color
5. If there are greater than K leaves in the tree some set of leaves in the tree
must be merged (their representative colors averaged) together and a new
representative color stored in their parent
6. To select the leaves to be merged do step 7
7. Reducible nodes that have the largest depth in the tree should be chosen first.
They represent colors that lie closest together. If there is more than one group
of leaves at the maximum depth then:
a. Merge the leaves that represent the fewest number of pixels.
b. Reduce the leaves that represent the most pixels.
8. Stop

PROGRAM:

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <conio.h>


61
typedef unsigned char uchar;
typedef unsigned short ushort;

#define XVAL 4 /* x value */
#define YVAL 4 /* y value */
#define ZVAL 4 /* z value */
#define LEAF 128 /* leaf node */
#define INTL 256 /* internal node */

/*
* 1---5
* /| /|
* 0---4 |
* | 3-|-7
* |/ |/
* 2---6
*/
enum ot_parts
{
TFL, /* TOP FRONT LEFT */
TFR, /* TOP FRONT RIGHT */
TBL, /* TOP BACK LEFT */
TBR, /* TOP BACK RIGHT */
BFL, /* BOTTOM FRONT LEFT */
BFR, /* BOTTOM FRONT RIGHT */
BBL, /* BOTTOM BACK LEFT */
BBR /* BOTTOM BACK RIGHT */
};

class ot_node_class
{
public:
ushort index;
uchar value;
ot_node_class **child;

ot_node_class(int ntype)
{
index = 0;
value = 0;
if (ntype == LEAF) /* node type */
{
child = NULL;
}
else
{

62
child = new ot_node_class*[8];

child[TFL] = NULL;
child[TFR] = NULL;
child[TBL] = NULL;
child[TBR] = NULL;
child[BFL] = NULL;
child[BFR] = NULL;
child[BBL] = NULL;
child[BBR] = NULL;
}
}

~ot_node_class()
{
if (child)
{
delete child[TFL];
delete child[TFR];
delete child[TBL];
delete child[TBR];
delete child[BFL];
delete child[BFR];
delete child[BBL];
delete child[BBR];
}
}

void ot_print()
{
printf(" %2d\t", value);
}

uchar avg_child(); /* average child */
};

uchar ot_node_class::avg_child() /* average child */
{
if (child)
{
ushort tmp = 0;
for (int i = 0; i < 8; i++)
{
tmp += (ushort)child[i];
}
return (uchar)(tmp /= 8);

63
}
return 0;
}

class data_array_class
{
public:
uchar data[XVAL][YVAL][ZVAL];
data_array_class() { }
~data_array_class() { }
void read_data();
ot_node_class *buildtree(int xpt = 0, int ypt = 0, int zpt = 0, int len=XVAL);
};

void data_array_class::read_data()
{
for (int i = 0; i < ZVAL; i++)
{
for (int j = 0; j < YVAL; j++)
{
for (int k = 0; k < XVAL; k++)
{
data[k][j][i] = rand() % 100;
printf(" [%d-%d-%d]:%2d\t", k, j, i, data[k][j][i]);
}
}
}
putchar('\n');
}

ot_node_class* data_array_class::buildtree(int xpt, int ypt, int zpt, int len)
{
ot_node_class *parent;

if (len == 1)
{
parent = new ot_node_class(LEAF);
parent->value = data[xpt][ypt][zpt];
return parent;
}
parent = new ot_node_class(INTL);
parent->child[TFL] = buildtree(xpt, ypt, zpt, len/2);
parent->child[TFR] = buildtree(xpt, ypt, zpt+len/2, len/2);
parent->child[TBL] = buildtree(xpt, ypt+len/2, zpt, len/2);
parent->child[TBR] = buildtree(xpt, ypt+len/2, zpt+len/2, len/2);
parent->child[BFL] = buildtree(xpt+len/2, ypt, zpt, len/2);

64
parent->child[BFR] = buildtree(xpt+len/2, ypt, zpt+len/2, len/2);
parent->child[BBL] = buildtree(xpt+len/2, ypt+len/2, zpt, len/2);
parent->child[BBR] = buildtree(xpt+len/2, ypt+len/2, zpt+len/2, len/2);
parent->value = parent->avg_child();
return parent;
}


class octree_class
{
public:
ot_node_class *root;
octree_class(ot_node_class *otree)
{
root = otree;
}
~octree_class()
{
delete root;
}
void depth_traversal(ot_node_class *recur_root = NULL, char *octnode_fun =
"ot_print");
};
void octree_class::depth_traversal(ot_node_class *recur_root, char *octnode_fun)
{
if (recur_root == NULL)
{
return;
}
if (!(recur_root->child))
{
if(!(strcmp(octnode_fun, "ot_print")))
{
recur_root->ot_print();
}
return;
}
for (int i = 0; i < 8; i++)
{
depth_traversal(recur_root->child[i], octnode_fun);
}
}

int main()
{
data_array_class dataobj;

65
clrscr();
printf("\n Implementing Octree \n");
printf("\n Reading three dimensional random data... \n");
dataobj.read_data();

printf("\n Building Octree using three dimensional random data... \n");
octree_class otobj(dataobj.buildtree());

printf("\n Depth Traversing Octree... \n");
printf(" Octree nodes are : \n");
otobj.depth_traversal(otobj.root, "ot_print");
putchar('\n');
getch();
return 0;
}

OUTPUT:

IMPLEMENTING OCTREE

Reading three dimensional random data...
[0-0-0]:46 [1-0-0]:30 [2-0-0]:82 [3-0-0]:90 [0-1-0]:56
[1-1-0]:17 [2-1-0]:95 [3-1-0]:15 [0-2-0]:48 [1-2-0]:26
[2-2-0]: 4 [3-2-0]:58 [0-3-0]:71 [1-3-0]:79 [2-3-0]:92
[3-3-0]:60 [0-0-1]:12 [1-0-1]:21 [2-0-1]:63 [3-0-1]:47
[0-1-1]:19 [1-1-1]:41 [2-1-1]:90 [3-1-1]:85 [0-2-1]:14
[1-2-1]: 9 [2-2-1]:52 [3-2-1]:71 [0-3-1]:79 [1-3-1]:16
[2-3-1]:81 [3-3-1]:51 [0-0-2]:95 [1-0-2]:93 [2-0-2]:34
[3-0-2]:10 [0-1-2]:79 [1-1-2]:95 [2-1-2]:61 [3-1-2]:92
[0-2-2]:89 [1-2-2]:88 [2-2-2]:66 [3-2-2]:64 [0-3-2]:92
[1-3-2]:63 [2-3-2]:66 [3-3-2]:64 [0-0-3]:39 [1-0-3]:51
[2-0-3]:27 [3-0-3]: 0 [0-1-3]:95 [1-1-3]:12 [2-1-3]: 8
[3-1-3]:66 [0-2-3]:47 [1-2-3]:42 [2-2-3]:74 [3-2-3]:69
[0-3-3]:89 [1-3-3]:83 [2-3-3]:66 [3-3-3]:41

Building Octree using three dimensional random data...

Depth Traversing Octree...

66
Octree nodes are :
46 12 56 19 30 21 17 41 95 39
79 95 93 51 95 12 48 14 71 79
26 9 79 16 89 47 92 89 88 42
63 83 82 63 95 90 90 47 15 85
34 27 61 8 10 0 92 66 4 52
92 81 58 71 60 51 66 74 66 66
64 69 64 41

RESULT:
Thus, the program has been executed and output is verified.





















67
Exp.No:- 15
DATE:- 23.08.2014

IMPLEMENTING QUAD TREES
AIM:
To implement quad trees in C language

THEORY:
A quadtree is a tree data structure in which each internal node has exactly four
children. Quadtrees are most often used to partition a two-dimensional space by
recursively subdividing it into four quadrants or regions. The regions may be square or
rectangular, or may have arbitrary shapes. This data structure was named a quadtree
by Raphael Finkel and J.L. Bentley in 1974. A similar partitioning is also known as a Q-
tree. All forms of quadtrees share some common features:
They decompose space into adaptable cells
Each cell (or bucket) has a maximum capacity. When maximum capacity is reached,
the bucket splits
The tree directory follows the spatial decomposition of the quadtree.

Each node in the quadtree has several properties:
nodes - a sparse array of the four child nodes in order: top-left, top-right, bottom-
left, bottom-right

68
leaf - a boolean indicating whether this is an internal node or a leaf node
point - the point associated with this node, if any (may apply to either internal or
leaf nodes)
x - the x-coordinate of the associated point, if any
y - the y-coordinate of the associated point, if any
The returned root node also defines add and visit methods.
INPUT:
Integer node, locational code of node to move;
Integer l, level of node;
Real x0, last known x-position of zone;
Real x1, new x-position of zone;
Real pw, width of a pixel;

ALGORITHM:
1. Start.
2. Compute number of whole pixels moved ((x1 x0)/pw) and store in Tx;
3. Find lowest bit position of Tx and store in j;
4. if j l then do step 5 to 7 else goto step 9
5. Bit-deinterleave node into nodex and nodey (1010{11,00});
6. Bit-interleave {nodex+Tx, nodey} and store in newnode;
7. Insert newnode into the Quadtree list with level l;
8. Delete node from the Quadtree list with level l;goto step12.
9. Delete node from the Quadtree list with level l;
10. Insert the four child nodes of node with level l 1;
11. Recursively apply this procedure to the four child nodes;
12. end if
13. Stop

PROGRAM:

#include <stdio.h>
#include <stdlib.h>

69
#include <ctype.h>
#include <conio.h>

#define MAX_N 512

unsigned char xbm[MAX_N][MAX_N/8]; /* image/graphics in the XBM format */
const int n = 16; /* image size */

typedef struct qt_node* qtree;

/*
* +----+----+
* | NW | NE |
* +----+----+
* | SW | SE |
* +----+----+
*/
typedef struct qt_node
{
char c;
qtree nw; /* north west (top left) */
qtree ne; /* north east (top right) */
qtree sw; /* south west (bottom left) */
qtree se; /* south east (bottom right) */
} node;

/* quad tree encode input */
static unsigned char img[] = {
0xf0,0xf0,
0xf0,0xf0,
0xf0,0xf0,
0xf0,0xf0,
0x0f,0x0f,
0x0f,0x0f,
0x0f,0x0f,
0x0f,0x0f,
0xf0,0xf0,
0xf0,0xf0,
0xf0,0xf0,
0xf0,0xf0,
0x0f,0x0f,
0x0f,0x0f,
0x0f,0x0f,
0x0f,0x0f,
};
/* quad tree decode input */

70
static char *qt_nodes = "QQWBBWQWBBWQWBBWQWBBW";
static qtree qt_simplify(qtree q)
{
if (q->c != 'Q')
{
return q;
}
if (q->nw->c=='W' && q->ne->c=='W' &&
q->sw->c=='W' && q->se->c=='W')
{

/* QWWWW -> W */
free(q->nw);
free(q->ne);
free(q->sw);
free(q->se);

q->c = 'W';

return q;
}
if (q->nw->c=='B' && q->ne->c=='B' &&
q->sw->c=='B' && q->se->c=='B')
{
/* QBBBB -> B */
free(q->nw);
free(q->ne);
free(q->sw);
free(q->se);

q->c = 'B';

return q;
}
return q;
}

static qtree qt_encode(int top, int left, int sz)
{
qtree q = (qtree)malloc(sizeof(node));
if (sz == 1)
{
q->c = xbm[top][left/8] & (1<<(left%8)) ? 'B' : 'W';
q->nw = NULL;
q->ne = NULL;
q->sw = NULL;

71
q->se = NULL;
}
else
{
q->c = 'Q';
q->nw = qt_encode(top, left, sz/2); /* nw */
q->ne = qt_encode(top, left+sz/2, sz/2); /* ne */
q->sw = qt_encode(top+sz/2, left, sz/2); /* sw */
q->se = qt_encode(top+sz/2, left+sz/2, sz/2); /* se */
}
return qt_simplify(q);
}

static void qt_decode(int top, int left, int sz)
{
int i, j;
static int k = 0; /* must be static */
char c = qt_nodes[k++];

switch (c)
{
case 'W':
{
for (i = top; i < (top + sz); i++)
{
for (j = left; j < (left + sz); j++)
{
xbm[i][j/8] &= ~(1 << (j%8)); /* clear */
}
}

break;
}

case 'B':
{
for (i = top; i < (top + sz); i++)
{
for (j = left; j < (left + sz); j++)
{
xbm[i][j/8] |= 1 << (j%8); /* set */
}
}

break;
}

72

case 'Q':
{
qt_decode(top, left, sz/2); /* nw */
qt_decode(top, left+sz/2, sz/2); /* ne */
qt_decode(top+sz/2, left, sz/2); /* sw */
qt_decode(top+sz/2, left+sz/2, sz/2); /* se */
}
}
}

static void qt_print(qtree q)
{
putchar(q->c);

if (q->c == 'Q')
{
qt_print(q->nw);
qt_print(q->ne);
qt_print(q->sw);
qt_print(q->se);
}
}

int main()
{
int i, j;
char ch;
clrscr();
puts("\n Implementing Quad Tree ");
do
{
printf("\n Enter your choice [ Encode (E) / Decode (D) / Exit (X) ] : ");
printf("%c", ch = getch());
ch = toupper(ch);
putchar('\n');
if ('E' == ch)
{
int k = 0;
for (i = 0; i < n; i++)
{
for (j = 0; j < n/8; j++)
{
xbm[i][j] = *(img+(k++));
}
}

73
printf(" Quadtree Width/Height : %d \n", n);
printf(" Quadtree Nodes : \n ");
qt_print(qt_encode(0, 0, n));
/* building quad tree from image*/
printf("\n");
}
else if ('D' == ch)
{
qt_decode(0, 0, n); /* retrieving image from quad tree */
printf(" Image size : %d \n", n);
printf(" static unsigned char img[] = { \n ");

for (i = 0; i < n; i++)
{
for (j = 0; j < n/8; j++)
{
printf("0x%02x,", xbm[i][j]);
}
printf("\n ");
}
printf("};\n");
}
else if ('X' == ch)
{
break;
}
} while (1);

return 0;
}

OUTPUT:
QUAD TREE
Enter your choice [ Encode (E) / Decode (D) / Exit (X) ] : E
Quadtree Width/Height : 16
Quadtree Nodes :
QQWBBWQWBBWQWBBWQWBBW

Enter your choice [ Encode (E) / Decode (D) / Exit (X) ] : D
Image size : 16
static unsigned char img[] = {

74
0xf0,0xf0,
0xf0,0xf0,
0xf0,0xf0,
0xf0,0xf0,
0x0f,0x0f,
0x0f,0x0f,
0x0f,0x0f,
0x0f,0x0f,
0xf0,0xf0,
0xf0,0xf0,
0xf0,0xf0,
0xf0,0xf0,
0x0f,0x0f,
0x0f,0x0f,
0x0f,0x0f,
0x0f,0x0f,
};

Enter your choice [ Encode (E) / Decode (D) / Exit (X) ] :X


RESULT:
Thus, the program has been executed and output is verified.




















75
MINI PROJECT
IMPLEMENTATION OF THREADED BST AND ITS OPERATIONS

ABSTRACT
Implementation of all operations of threaded binary search tree using C
programming language

1. INTRODUCTION
"A binary tree is threaded by making all right child pointers that would normally be null
point to the inorder successor of the node (if it exists) , and all left child pointers that
would normally be null point to the inorder predecessor of the node."


2. PROPOSED SYSTEM
This project is proposed to implement complex data structure: threaded binary search
tree and its operations such as creation threaded BST, insertion of node in the threaded
BST, and deletion of existing node from threaded BST, in-order traversal of threaded
BST, by using C programming language

3. SOFTWARE AND HARDWARE ENVIRONMENT

Software : Borland Turbo C++ Version 3.0

Operation System : Windows XP / Windows NT


4. PROBLEM DEFINITION

FEATURES OF THREADED BINARY TREE:
A threaded binary tree makes it possible to traverse the values in the binary tree via a
linear traversal that is more rapid than a recursive in-order traversal.
It is also possible to discover the parent of a node from a threaded binary tree, without
explicit use of parent pointers or a stack. This can be useful where stack space is
limited, or where a stack of parent pointers is unavailable
Threaded binary tree improve the processing speed

76

TYPES OF THREADED BINARY TREES:
Single Threaded: each node is threaded towards either(right)' the in-order
predecessor or' successor.
Double threaded: each node is threaded towards both(left & right)' the in-order
predecessor and' successor

THE ARRAY OF INORDER TRAVERSAL:
Threads are reference to the predecessors and successors of the node according to an
inorder traversal.
Inorder of the threaded tree is ABCDEFGHI, the predecessor of E is D, the successor of
E is F.

EXAMPLE:

50







(a) Binary Search Tree


50








(b) Threaded Binary Search Tree
In the above threaded binary search tree, the left-child thread of node 15, and right
child thread of node 55 are called loose threads. To avoid these lose threads, we add
one dummy root node.
Based on dummy root node, the definition of threaded binary tree: A threaded binary
search tree is the left sub-tree of the root node whose right child pointer points to
25 0
0 55 0
0 25 0
25
55
25

77
itself. So that, after adding dummy root node, the above threaded binary search tree,
look like as follows:




50








To keep track of which pointer are threads and which are normal pointer, we have
two additional boolean fields in each node. Let the field be FPPOINT and TRPOINT
o If TLPOINT(node)=1 then the node contains normal pointer
o If TLPOINT(node)=0 then the node contains thread pointer
Similarly
o If TRPOINT(node)=1 then the node contains normal pointer
o If TRPOINT(node)=0 then the node contains thread pointer

The node structure is given below:














Threaded Binary Search Tree

OPERATIONS ON THREADED BINARY SEARCH TREE ARE:
(i) Insertion of new node
(ii) Deletion of existing node
(iii) Tree traversal

100


25
55
25
TLPOINT LCHILD DATA RCHILD TRPOINT
1
100

1
1
50

1
0 55 0
1
25 0
0 50 0
Dummy root node
The actual threaded
BST root node

78
(i) INSERTION OF NEW NODE
To perform an insertion of new node in the threaded binary search tree, follow the
step given below:
(a) find the parent node for the new node to be inserted in the tree using search
operation
(b) searching the parent of new node is done by using the following rule:
(i) start from root
(ii) if the data value of new node is less than data value of parent node, go left
(iii)if the data value of new node is greater than data value of parent node, go
right
(c) repeat step (b) until we find thread pointer and then insert the new node as either
left or right child by comparing new node value with parent node
EXAMPLE:









(a) before insertion of new child D (b) before insertion of new child D

(ii) DELETION OF EXISTING NODE
To perform deletion of existing node in the threaded binary search tree, follow the
step given below:
(a) Search the node to be deleted from threaded BST and name the node to be
deleted as temp and its parent node as par
(b) To delete node, we have to consider four cases given below:
Case 1: node to be deleted does not have children
Case 2: node to be deleted contain only left child
Case 3: node to be deleted contain only right child
Case 4: node to be deleted contain both children
Case 1: node to be deleted does not have children
Before deletion:










1
100

1
1
50

1
0

60

0 1 45 0
0 65 0
root

A
B
C D
parent
child
root

A
B
C D
parent
child
D
root

A
B
C
parent
child
par
temp (node to be deleted)

79
After deletion:









Case 4: node to be deleted does have both children

Before deletion:















After deletion:

















1
100

1
1
50

1
0 60 0 1 45 0
1
100
1
1
50

1
0

60

0 1 45 0
0 65

0
0 64 0
0 66 0
1
100
1
1
45

1
0

60

0
0 65

0
0 64 0
0 66 0
par
par
node to be leleted (temp, prepare)

80
(iii) TREE TRAVERSAL
We use in-order traversal, to search the threaded BST. To achieve in-order traversal, we
proceed from each given node to its inorder successor. The inorder successor is
determined by one of two methods:
(a) If the right child pointer of the node is a thread then it lead us directly to the in-
order successor
(b) Otherwise goto the right child pointer of that node and from there go deep left
until a left thread is found


5. ALGORITHM

Creation of dummy node
1. Create a dummy root node whose right-hand child contains normal pointer
pointing to itself and left-child contain thread pointer pointing to itself
root1->data=100;
root1->llink=root1;
root1->rlink=root1;
root1->tlpoint=0;
root1->trpoint=1;

Insertion operation
1. Read the elements to be inserted and name this node as ptr
2. If the tree contain only dummy root node then
a. Make this new node as left child to the dummy root node and make
dummy root node left threaded pointer has 1
3. Otherwise
a. Search the parent node for the new node and mark parent node as par
b. Insert the new node as left child or right child to parent and change the
threaded pointer for the parent node and new node based on in-order rule:

if(t<par->data)
{
ptr->llink=par->llink;
ptr->rlink=par;
par->llink=ptr;
par->tlpoint=1;
}
else
{
ptr->rlink=par->rlink;
ptr->llink=par;
par->rlink=ptr;
par->trpoint=1;
}


81
Deletion operation
1. To perform deletion operation search the element to be deleted .If found mark
that node as temp and its parent node as par.
2. check the temp node comes under what case
case i) : temp node does not have children
a. if the node to be deleted is actual root node
make dummy root node left child to point itself and left thread pointer as 0
if(temp==root->llink)
{
root1->llink =root1;
root1->tlpoint = 0;
}
b. if the node to be deleted is leaf node
based on the value of the node to be deleted change the parents
left child
or right child pointer and its thread pointer as 0
if(temp->data < par->data)
{
par-> llink=temp -> llink;
par->tlpoint = 0;
}
else
{
par->rlink=temp->rlink;
par->trpoint=0;
}

case ii) : temp node contains only left child
a) if the node to be deleted is actual root node
make its left child as actual root node and change the thread pointer value.

b) if it node to deleted is non-terminal node.

case iii) : temp node contains only right child
a) if the node to be deleted is actual root node
make its right child as actual root node and change the thread pointer
value.

b) if it node to deleted is non-terminal node.
make its parent node to point to its right child and change the thread
pointer value.

case iv) : temp node contains both children
a) make temp node as prepar node
b) make temp left child as par node
c) check par node contains right child

82
d) if right child is there make per node as prepar node and par right child as
par
e) repeat step d until nor more right child is found.
f) replace temp -> data with par -> data
prepar = temp
par = temp -> llink;
while(par -> trpoint !=0)
{
prepar = par;
par=par->rlink;
}
temp -> data = par -> data;

g) par node contains left child apply case ii procedure
h) else make prepar left child as par left child and change its thread pointer
value

if(par -> tlpoint = = 0)
{
if(par -> data > prepar -> data)
{
prepar -> rlink = par -> rlink)
prepar -> trpoint = 0;
}
else if(par -> data <= prepar -> data)
{
prepar -> llink = par -> llink)
prepar -> trpoint = 0;
}
}

Displaying using inorder traversing

1. the inorder successor
a. If the right child pointer of the node is a thread then it lead us directly to
the in-order successor
b. Otherwise goto the right child pointer of that node and from there go deep
left until a left thread is found
do
{
if(!p->trpoint)
p=p->rlink;
else
{
//find the right sub tree
p=p->rlink;

83
//move to the deepest level of left sub tree until thread pointer is
found
while(p->tlpoint)
p=p->llink;
}
if(p!=root1)
cout << p-> data << -> ;
}while(p!=root1);
cout<<endl<<endl;

6. OUTPUT

1. Creation
2. Insertion
3. Deletion
4. Inorder notation
5. Exit

Enter the choice : 1

Dummy header successfully created...

1. Creation
2. Insertion
3. Deletion
4. Inorder notation
5. Exit

Enter the choice : 2

CREATION OF THREADED BINARY SEARCH TREE
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
ENTER ITEM TO INSERT( 0 - EXIT )5
ENTER ITEM TO INSERT( 0 - EXIT )15
ENTER ITEM TO INSERT( 0 - EXIT )10
ENTER ITEM TO INSERT( 0 - EXIT )25
ENTER ITEM TO INSERT( 0 - EXIT )30
ENTER ITEM TO INSERT( 0 - EXIT )0


1. Creation
2. Insertion
3. Deletion
4. Inorder notation
5. Exit


84
Enter the choice : 4

Inorder notation of TBST : 5->10->15->25->30->



1. Creation
2. Insertion
3. Deletion
4. Inorder notation
5. Exit

Enter the choice : 3

Before deletion the elements are :
Inorder notation of TBST : 5->10->15->25->30->

Enter the element to be delete :15

After deletion the elements are :5
Inorder notation of TBST : 5->10->25->30->


7. CONCLUSION

Threaded binary search tree successfully implemented using C language and tested with
set of possible inputs


8. BIBLIOGRAPHY

(i) Data Structure Through C by Yashavant P. Kanetkar, BPB Publication
(ii) Data Structures, Algorithms and Applications in C++ by Sartaj Sahni,
Universities Press
(iii) Data Structures and Algorithms in C++ by B.M. Harwani, Dream Tech Press

You might also like