0% found this document useful (0 votes)
79 views30 pages

Binary Tree - Set 1 (Introduction) : 8.implementation of Trees, Tree Traversals

The document discusses binary search trees (BSTs), including their properties, how to search for a key in a BST, and how to insert a new key into a BST. Some key points: - A BST is a binary tree where all left descendants of a node are less than or equal to the node, and all right descendants are greater than or equal. - To search a BST, start at the root and recursively check left or right subtrees depending on if the key is less than or greater than the current node's key. - To insert a new key, search for the key as if searching, but when a leaf is reached, insert the new node as the leaf node.

Uploaded by

Anand Duraiswamy
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
79 views30 pages

Binary Tree - Set 1 (Introduction) : 8.implementation of Trees, Tree Traversals

The document discusses binary search trees (BSTs), including their properties, how to search for a key in a BST, and how to insert a new key into a BST. Some key points: - A BST is a binary tree where all left descendants of a node are less than or equal to the node, and all right descendants are greater than or equal. - To search a BST, start at the root and recursively check left or right subtrees depending on if the key is less than or greater than the current node's key. - To insert a new key, search for the key as if searching, but when a leaf is reached, insert the new node as the leaf node.

Uploaded by

Anand Duraiswamy
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 30

EX8

8.IMPLEMENTATION OF TREES, TREE TRAVERSALS

Binary Tree | Set 1 (Introduction)


Trees: Unlike Arrays, Linked Lists, Stack and queues, which are linear data structures, trees are hierarchical data
structures.
Tree Vocabulary: The topmost node is called root of the tree. The elements that are directly under an element are
called its children. The element directly above something is called its parent. For example, ‘a’ is a child of ‘f’, and
‘f’ is the parent of ‘a’. Finally, elements with no children are called leaves.
tree
----
j <-- root
/ \
f k
/ \ \
a h z <-- leaves

Why Trees?
1. One reason to use trees might be because you want to store information that naturally forms a hierarchy. For
example, the file system on a computer:
file system
-----------
/ <-- root
/ \
... home
/ \
ugrad course
/ / | \
... cs101 cs112 cs113

2. Trees (with some ordering e.g., BST) provide moderate access/search (quicker than Linked List and slower than
arrays).
3. Trees provide moderate insertion/deletion (quicker than Arrays and slower than Unordered Linked Lists).
4. Like Linked Lists and unlike Arrays, Trees don’t have an upper limit on number of nodes as nodes are linked
using pointers.
Main applications of trees include:
1. Manipulate hierarchical data.
2. Make information easy to search (see tree traversal).
3. Manipulate sorted lists of data.
4. As a workflow for compositing digital images for visual effects.
5. Router algorithms
6. Form of a multi-stage decision-making (see business chess).

Binary Tree: A tree whose elements have at most 2 children is called a binary tree. Since each element in a binary
tree can have only 2 children, we typically name them the left and right child.
Binary Tree Representation in C: A tree is represented by a pointer to the topmost node in tree. If the tree is
empty, then value of root is NULL.
A Tree node contains following parts.
1. Data
2. Pointer to left child
3. Pointer to right child
In C, we can represent a tree node using structures. Below is an example of a tree node with an integer data.
Record:
AIM:
To write a c program to traverse the tree recursively.

ALGORITHM:
Step1: Create the structure node.
Step2: Declare the functions generate(),infix(),postfix(),prefix()and delete().
Step3: Read the choice if it is insert then it process the following
a) Check if header pointer is null then memory is allocated using malloc() and
the header pointer is pointed to the num.
b) If num is greater than prev then insert the element to right.
c) If num is lesser than prev then insert the element to left.
Step4: if it is infix traversal then it process the following function calling
a) Traverse the left subtree
b) Visit the root
c) Traverse the right subtree
Step5: if it is preorder traversal then it process the following function calling
a) Visit the root
b) Traverse the left subtree
c) Traverse the right subtree
Step6: if it is post order traversal then it process the following function calling
a) Traverse the left subtree
b) Traverse the right subtree
c) Visit the root
Step7:Display the results.

PROGRAM:
#include <stdio.h>
#include <stdlib.h>
struct node
{
int a;
struct node *left;
struct node *right;
};
void generate(struct node **, int);
void infix(struct node *);
void postfix(struct node *);
void prefix(struct node *);
void delete(struct node **);
int main()
{
struct node *head = NULL;
int choice = 0, num, flag = 0, key;
do
{
printf("\nEnter your choice:\n1. Insert\n2. Traverse via infix\n3.Traverse via
prefix\n4. Traverse via postfix\n5. Exit\nChoice: ");
scanf("%d", &choice);
switch(choice)
{
case 1:
printf("Enter element to insert: ");
scanf("%d", &num);
generate(&head, num);
break;
case 2:
infix(head);
break;
case 3:
prefix(head);
break;
case 4:
postfix(head);
break;
case 5:
delete(&head);
printf("Memory Cleared\nPROGRAM TERMINATED\n");
break;
default: printf("Not a valid input, try again\n");
}
} while (choice != 5);
return 0;
}
void generate(struct node **head, intnum)
{
struct node *temp = *head, *prev = *head;
if (*head == NULL)
{
*head = (struct node *)malloc(sizeof(struct node));
(*head)->a = num;
(*head)->left = (*head)->right = NULL;
}
else
{
while (temp != NULL)
{
if (num> temp->a)
{
prev = temp;
temp = temp->right;
}
else
{
prev = temp;
temp = temp->left;
}
}
temp = (struct node *)malloc(sizeof(struct node));
temp->a = num;
if (num>= prev->a)
{
prev->right = temp;
}
else
{
prev->left = temp;
}
}
}
void infix(struct node *head)
{
if (head)
{
infix(head->left);
printf("%d ", head->a);
infix(head->right);
}
}
void prefix(struct node *head)
{
if (head)
{
printf("%d ", head->a);
prefix(head->left);
prefix(head->right);
}
}
void postfix(struct node *head)
{
if (head)
{
postfix(head->left);
postfix(head->right);
printf("%d ", head->a);
}
}
void delete(struct node **head)
{
if (*head != NULL)
{
if ((*head)->left)
{
delete(&(*head)->left);
}
if ((*head)->right)
{
delete(&(*head)->right);
}
free(*head);
}
}

SAMPLE OUTPUT:
Enter your choice:
1. Insert
2. Traverse via infix
3.Traverse via prefix
4. Traverse via postfix
5. Exit
Choice:1
Enter element to insert: 7
Enter your choice:
1. Insert
2. Traverse via infix
3.Traverse via prefix
4. Traverse via postfix
5. Exit
Choice:1
Enter element to insert:3
Enter your choice:
1. Insert
2. Traverse via infix
3.Traverse via prefix
4. Traverse via postfix
5. Exit
Choice:1
Enter element to insert: 8
Enter your choice:
1. Insert
2. Traverse via infix
3.Traverse via prefix
4. Traverse via postfix
5. Exit
Choice:1
Enter element to insert: 2
Enter your choice:
1. Insert
2. Traverse via infix
3.Traverse via prefix
4. Traverse via postfix
5. Exit
Choice: 2
2 3 7 8
Enter your choice:
1. Insert
2. Traverse via infix
3.Traverse via prefix
4. Traverse via postfix
5. Exit
Choice:3
7 3 2 8
Enter your choice:
1. Insert
2. Traverse via infix
3.Traverse via prefix
4. Traverse via postfix
5. Exit
Choice: 4
2 3 8 7
Enter your choice:
1. Insert
2. Traverse via infix
3.Traverse via prefix
4. Traverse via postfix
5. Exit
Choice:5
Memory cleared
Program terminated

RESULT:
Thus the C program to implement tree and traverse the tree elements are performed and
output was verified successfully.
9.Binary Search Tree | Set 1 (Search and Insertion)
The following is definition of Binary Search Tree(BST) according to Binary Search Tree, is a node-based
binary tree data structure which has the following properties:
 The left subtree of a node contains only nodes with keys lesser than the node’s key.
 The right subtree of a node contains only nodes with keys greater than the node’s key.
 The left and right subtree each must also be a binary search tree.
There must be no duplicate nodes.

The above properties of Binary Search Tree provide an ordering among keys so that the operations like
search, minimum and maximum can be done fast. If there is no ordering, then we may have to compare
every key to search a given key.

Searching a Key
To search a given key in Binary Search Tree, we first compare it with root, if the key is present at root, we
return root. If key is greater than root’s key, we recur for right subtree of root node. Otherwise we recur for
left subtree.

Illustration to search 6 in below tree:


1. Start from root.
2. Compare the inserting element with root, if less than root, then recurse for left, else recurse for right.
3. If element to search is found anywhere, return true, else return false.

Insertion of a key
A new key is always inserted at leaf. We start searching a key from root till we hit a leaf
node. Once a leaf node is found, the new node is added as a child of the leaf node.
100 100

/ \ Insert 40 / \

20 500 ---------> 20 500

/ \ / \

10 30 10 30

\
40

Program:
#include <stdio.h>

#include <stdlib.h>

struct btnode

int value;

struct btnode *l;

struct btnode *r;

}*root = NULL, *temp = NULL, *t2, *t1;

void delete1();

void insert();

void delete();

void inorder(struct btnode *t);

void create();

void search(struct btnode *t);

void preorder(struct btnode *t);

void postorder(struct btnode *t);

void search1(struct btnode *t,int data);

int smallest(struct btnode *t);

int largest(struct btnode *t);

int flag = 1;

void main()
{

int ch;

printf("\nOPERATIONS ---");

printf("\n1 - Insert an element into tree\n");

printf("2 - Delete an element from the tree\n");

printf("3 - Inorder Traversal\n");

printf("4 - Preorder Traversal\n");

printf("5 - Postorder Traversal\n");

printf("6 - Exit\n");

while(1)

printf("\nEnter your choice : ");

scanf("%d", &ch);

switch (ch)

case 1:

insert();

break;

case 2:

delete();

break;

case 3:

inorder(root);

break;

case 4:

preorder(root);

break;
case 5:

postorder(root);

break;

case 6:

exit(0);

default :

printf("Wrong choice, Please enter correct choice ");

break;

/* To insert a node in the tree */

void insert()

create();

if (root == NULL)

root = temp;

else

search(root);

/* To create a node */

void create()

int data;

printf("Enter data of node to be inserted : ");


scanf("%d", &data);

temp = (struct btnode *)malloc(1*sizeof(struct btnode));

temp->value = data;

temp->l = temp->r = NULL;

/* Function to search the appropriate position to insert the new node */

void search(struct btnode *t)

if ((temp->value > t->value) && (t->r != NULL)) /* value more than root node value insert at right */

search(t->r);

else if ((temp->value > t->value) && (t->r == NULL))

t->r = temp;

else if ((temp->value < t->value) && (t->l != NULL)) /* value less than root node value insert at left */

search(t->l);

else if ((temp->value < t->value) && (t->l == NULL))

t->l = temp;

/* recursive function to perform inorder traversal of tree */

void inorder(struct btnode *t)

if (root == NULL)

printf("No elements in a tree to display");

return;

if (t->l != NULL)
inorder(t->l);

printf("%d -> ", t->value);

if (t->r != NULL)

inorder(t->r);

/* To check for the deleted node */

void delete()

int data;

if (root == NULL)

printf("No elements in a tree to delete");

return;

printf("Enter the data to be deleted : ");

scanf("%d", &data);

t1 = root;

t2 = root;

search1(root, data);

/* To find the preorder traversal */

void preorder(struct btnode *t)

if (root == NULL)

{
printf("No elements in a tree to display");

return;

printf("%d -> ", t->value);

if (t->l != NULL)

preorder(t->l);

if (t->r != NULL)

preorder(t->r);

/* To find the postorder traversal */

void postorder(struct btnode *t)

if (root == NULL)

printf("No elements in a tree to display ");

return;

if (t->l != NULL)

postorder(t->l);

if (t->r != NULL)

postorder(t->r);

printf("%d -> ", t->value);

/* Search for the appropriate position to insert the new node */

void search1(struct btnode *t, int data)

{
if ((data>t->value))

t1 = t;

search1(t->r, data);

else if ((data < t->value))

t1 = t;

search1(t->l, data);

else if ((data==t->value))

delete1(t);

/* To delete a node */

void delete1(struct btnode *t)

int k;

/* To delete leaf node */

if ((t->l == NULL) && (t->r == NULL))

if (t1->l == t)

t1->l = NULL;

}
else

t1->r = NULL;

t = NULL;

free(t);

return;

/* To delete node having one left hand child */

else if ((t->r == NULL))

if (t1 == t)

root = t->l;

t1 = root;

else if (t1->l == t)

t1->l = t->l;

else

t1->r = t->l;

t = NULL;

free(t);
return;

/* To delete node having right hand child */

else if (t->l == NULL)

if (t1 == t)

root = t->r;

t1 = root;

else if (t1->r == t)

t1->r = t->r;

else

t1->l = t->r;

t == NULL;

free(t);

return;

/* To delete node having two child */

else if ((t->l != NULL) && (t->r != NULL))

t2 = root;

if (t->r != NULL)

k = smallest(t->r);

flag = 1;
}

else

k =largest(t->l);

flag = 2;

search1(root, k);

t->value = k;

/* To find the smallest element in the right sub tree */

int smallest(struct btnode *t)

t2 = t;

if (t->l != NULL)

t2 = t;

return(smallest(t->l));

else

return (t->value);

/* To find the largest element in the left sub tree */

int largest(struct btnode *t)

{
if (t->r != NULL)

t2 = t;

return(largest(t->r));

else

return(t->value);

}
EX:10 SEARCHING
a)Linear Search:
#include<stdio.h>

#include<conio.h>

void main(void)

int i,j,a[10],n;

printf("\nEnter No.Of Elements:");

scanf("%d",&n);

printf("\nEnter Element :\n");

for(i=0;i<n;i++)

printf("\nEnter a[%d] Element:",i+1);

scanf("%d",&a[i]);

for(i=0;i<n;i++)

printf("\na[%d] = %d",i+1,a[i]);

printf("\nEnter Element To Search ");

scanf("%d",&j);

for(i=0;i<n;i++)

if(a[i]==j)

printf("\nSearched Element %d In %d th Position",j,i+1);

getch();
}

b)Binary Search:
#include <stdio.h>

void main()

int c, first, last, middle, n, search, array[100];

printf("Enter number of elements\n");

scanf("%d",&n);

printf("Elements Should Be In Ascending Order\n");

printf("Enter %d integers\n", n);

for (c = 0; c < n; c++)

scanf("%d",&array[c]);

printf("Enter value to find\n");

scanf("%d", &search);

first = 0;

last = n - 1;

middle = (first+last)/2;

while (first <= last) {

if (array[middle] < search)

first = middle + 1;
else if (array[middle] == search) {

printf("%d found at location %d.\n", search, middle+1);

break;

else

last = middle - 1;

middle = (first + last)/2;

if (first > last)

printf("Not found! %d isn't present in the list.\n", search);

getch();

}
EX 11

11. IMPLEMENTATION OF INSERTION SORT,BUBBLE SORT,QUICK SORT,MERGE


SORT

11(a)INSERTION SORT

AIM:

To write a C program to perform insertion sort.

ALGORITHM:
Step 1: Read the input list size.
Step 2: Read the list elements.
Step 3: pass=1
Step 4: Repeat the following steps until pass reach size-1 (for N-1 passes)
i) key=list[Pass]
ii) swap=pass-1
iii) Repeat the following steps if this condition is true list[swap]>key
and swap >= 0.(for comparison).
a) list [sawp+1]=list[swap ]
b) swap—
iv) list [swap+1]
Program:

#include<stdio.h>

int main()
{
int i,j,n,temp,a[30];
printf("\nEnter the number of elements:");
scanf("%d",&n);
printf("\nEnter the elements\n");

for(i=0;i<n;i++)
{
printf("Enter a[%d] = ",i+1);
scanf("%d",&a[i]);
}

for(i=1;i<=n-1;i++)
{
temp=a[i];
j=i-1;

while((temp<a[j])&&(j>=0))
{
a[j+1]=a[j]; //moves element forward
j=j-1;
}

a[j+1]=temp; //insert element in proper place


}

printf("\nSorted list is as follows\n");


for(i=0;i<n;i++)
{

printf("\na[%d] = %d ",i+1,a[i]);
}

return 0;
}

SAMPLE OUTPUT:
Enter number of terms(should be less than 100): 5
Enter elements: 12
5
2
8
3
In ascending order: 2 3 5 8 12

RESULT:
Thus the C program for Insertion sort was created, executed and output was
verified successfully.

11(b) Bubble Sort

AIM:

To write a C program to perform bubble sort.

ALGORITHM:
Step 1: Read the input list size.
Step 2: Read the list elements.
Step 3: Assign count =0
Step 4: Repeat the loop until count less than list size.(for n-1 passes)
a) Assign inner_count=count+1
b) Repeat the loop inner_count less than list size (for arrange the
list)
1) If list [count]> list [inner_count] (check element value )
2) temp = list [count]
3) list [count]=list[inner_count]
4) a[inner_count]=temp

Program:
#include<stdio.h>

int main()
{
int a[50],n,i,j,temp;
printf("Enter the size of array: ");
scanf("%d",&n);
printf("Enter the array elements: ");

for(i=0;i<n;++i)
{ printf("a[%d]=",i+1);
scanf("%d",&a[i]);
}
for(i=1;i<n;++i)
for(j=0;j<(n-i);++j)
if(a[j]>a[j+1])
{
temp=a[j];
a[j]=a[j+1];
a[j+1]=temp;
}

printf("\nArray after sorting: ");


for(i=0;i<n;++i)
printf("\na[%d]=%d \n ",i,a[i]);

return 0;
}

SAMPLE OUTPUT:
Enter number of terms(should be less than 100): 5
Enter elements: 12
5
2
8
3
In ascending order: 2 3 5 8 12

RESULT:
Thus the C program for Bubble sort was created, executed and output was
verified successfully.

11(c) QUICK SORT

AIM:

To write a C program to perform quick sort.

ALGORITHM:
Step1: Get the value of how many no. to be sorted.
Step2: Get the elements from the user.
Step3: Two function quicksort() and swap().
a) Quick sort to perform sorting.
b)Swap() is just to rearrange the values.
Step4: Quick sort algorithm works by partitioning the array to be sorted, then
recursively sorting each partition.
Step5:Display the sorted value.

Program:
#include <stdio.h>
void quick_sort(int[],int,int);
int partition(int[],int,int);
int main()
{
int a[50],n,i;
printf("How many elements?");
scanf("%d",&n);
printf("\nEnter array elements:");
for(i=0;i<n;i++)
scanf("%d",&a[i]);

quick_sort(a,0,n-1);
printf("\nArray after sorting:");
for(i=0;i<n;i++)
printf("%d ",a[i]);

return 0;
}

void quick_sort(int a[],int l,int u)


{
int j;
if(l<u)
{
j=partition(a,l,u);
quick_sort(a,l,j-1);
quick_sort(a,j+1,u);
}
}

int partition(int a[],int l,int u)


{
int v,i,j,temp;
v=a[l];
i=l;
j=u+1;

do
{
do
i++;

while(a[i]<v&&i<=u);

do
j--;
while(v<a[j]);

if(i<j)
{
temp=a[i];
a[i]=a[j];
a[j]=temp;
}
}while(i<j);

a[l]=a[j];
a[j]=v;

return(j);
}

SAMPLE OUTPUT:
Enter number of terms(should be less than 100): 5
Enter elements: 12
5
2
8
3
In ascending order: 2 3 5 8 12

RESULT:
Thus the C program for quicksort was created, executed and output was verified
successfully.

11(d) MERGE SORT

AIM:

To write a C program to perform Merge sort.

ALGORITHM:
Step1:If the list is of length 0 or 1, then it is already sorted. Otherwise:
Step2: Divide the unsorted list into two sublist of about half the size.
Step3: Sort each sublist recursively by re-applying merge sort.
Step4: Merge the two sublist back into one sorted list.

Program:
#include<stdio.h>
#include<conio.h>
void mergesort(int a[],int i,int j);
void merge(int a[],int i1,int j1,int i2,int j2);
void main()
{
int a[30],n,i;
clrscr();
printf("Enter no of elements:");
scanf("%d",&n);
printf("Enter array elements:");
for(i=0;i<n;i++)
scanf("%d",&a[i]);
mergesort(a,0,n-1);
printf("\nSorted array is:");
for(i=0;i<n;i++)
printf("%d",a[i]);
getch();
}
void mergesort(int a[],int i,int j)
{
int mid;
if(i<j)
{
mid=(i+j)/2;
mergesort(a,i,mid);
mergesort(a,mid+1,j);
merge(a,i,mid,mid+1,j);
}
}
void merge(int a[],int i1,int j1,int i2,int j2)
{
int temp[50];
int i,j,k;
i=i1;
j=i2;
k=0;
while(i<=j1&&j<=j2)
{
if(a[i]<a[j])
temp[k++]=a[i++];
else
temp[k++]=a[j++];
}
while(i<=j1)
temp[k++]=a[i++];
while(j<=j2)
temp[k++]=a[j++];
for(i=i1,j=0;i<=j2;i++,j++)
a[i]=temp[j];
}

SAMPLE OUTPUT:
Enter number of terms(should be less than 100): 5
Enter elements: 12
5
2
8
3
In ascending order: 2 3 5 8 12

RESULT:
Thus the C program for Merge sort was created, executed and output was verified
successfully.

You might also like