Binary Tree - Set 1 (Introduction) : 8.implementation of Trees, Tree Traversals
Binary Tree - Set 1 (Introduction) : 8.implementation of Trees, Tree Traversals
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.
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 / \
/ \ / \
10 30 10 30
\
40
Program:
#include <stdio.h>
#include <stdlib.h>
struct btnode
int value;
void delete1();
void insert();
void delete();
void create();
int flag = 1;
void main()
{
int ch;
printf("\nOPERATIONS ---");
printf("6 - Exit\n");
while(1)
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 :
break;
void insert()
create();
if (root == NULL)
root = temp;
else
search(root);
/* To create a node */
void create()
int data;
temp->value = data;
if ((temp->value > t->value) && (t->r != NULL)) /* value more than root node value insert at right */
search(t->r);
t->r = temp;
else if ((temp->value < t->value) && (t->l != NULL)) /* value less than root node value insert at left */
search(t->l);
t->l = temp;
if (root == NULL)
return;
if (t->l != NULL)
inorder(t->l);
if (t->r != NULL)
inorder(t->r);
void delete()
int data;
if (root == NULL)
return;
scanf("%d", &data);
t1 = root;
t2 = root;
search1(root, data);
if (root == NULL)
{
printf("No elements in a tree to display");
return;
if (t->l != NULL)
preorder(t->l);
if (t->r != NULL)
preorder(t->r);
if (root == NULL)
return;
if (t->l != NULL)
postorder(t->l);
if (t->r != NULL)
postorder(t->r);
{
if ((data>t->value))
t1 = t;
search1(t->r, data);
t1 = t;
search1(t->l, data);
else if ((data==t->value))
delete1(t);
/* To delete a node */
int k;
if (t1->l == t)
t1->l = NULL;
}
else
t1->r = NULL;
t = NULL;
free(t);
return;
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;
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;
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;
t2 = t;
if (t->l != NULL)
t2 = t;
return(smallest(t->l));
else
return (t->value);
{
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;
scanf("%d",&n);
for(i=0;i<n;i++)
scanf("%d",&a[i]);
for(i=0;i<n;i++)
printf("\na[%d] = %d",i+1,a[i]);
scanf("%d",&j);
for(i=0;i<n;i++)
if(a[i]==j)
getch();
}
b)Binary Search:
#include <stdio.h>
void main()
scanf("%d",&n);
scanf("%d",&array[c]);
scanf("%d", &search);
first = 0;
last = n - 1;
middle = (first+last)/2;
first = middle + 1;
else if (array[middle] == search) {
break;
else
last = middle - 1;
getch();
}
EX 11
11(a)INSERTION SORT
AIM:
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;
}
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.
AIM:
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;
}
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.
AIM:
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;
}
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.
AIM:
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.