(adsbygoogle = window.adsbygoogle || []).push({ google_ad_client: "ca-pub-2960223314593660", enable_page_level_ads: true }); Binary tree using array - TecGlance

Header Ads

Binary tree using array

#include <stdio.h>
#include <stdlib.h>
void build_tree(int tree[],int index)
{

char op1,op2;
if(index!=0)
{
printf("\nEnter the element: ");
scanf("%d",&tree[index]);
printf("\nCreate left node? (Y/N)");
fflush(stdin);
scanf("%c",&op1);
if ((op1=='Y')||(op1=='y'))
{
build_tree(tree,2*index);
}
else
{
build_tree(tree,0);
}
printf("\nCreate right node? (Y/N)");
fflush(stdin);
scanf("%c",&op2);
if ((op2=='Y')||(op2=='y'))
{
build_tree(tree,2*index+1);
}
else
{
build_tree(tree,0);
}
}
}
void tree_traversal(int tree[],int index)
{
if(tree[index]!=0)
{
printf("%d ",tree[index]);
tree_traversal(tree,2*index);
tree_traversal(tree,2*index+1);
}
}
int search_tree(int tree[],int item)
{
int i;
for(i=0;i<100;i++)
{
if(tree[i]==item)
{
return i;
break;
}
}
return 0;
}
void insert_tree(int tree[],int parent)
{
char opt;
int ptr,el;
ptr=search_tree(tree,parent);
if(ptr==0)
{
printf("\nElement not found!");
}
else
{
if((tree[ptr*2]==0)||(tree[ptr*2+1]==0))
{
printf("\nInsert as Left/Right child? (L/R)");
fflush(stdin);
scanf("%c",&opt);
if ((opt=='L')||(opt=='l'))
{
if(tree[ptr*2]==0)
{
printf("\nEnter the element: ");
scanf("%d",&tree[ptr*2]);
}
else
{
printf("\nInsertion not possible!");
}
}
else
{
if(tree[ptr*2+1]==0)
{
printf("\nEnter the element: ");
scanf("%d",&tree[ptr*2+1]);
}
else
{
printf("\nInsertion not possible!");
}
}
}
else
{
printf("\nInsertion not possible!");
}
}
}
int search_parent(int tree[],int item)
{
int i;
for(i=0;i<100;i++)
{
if(tree[i]==item)
{
if(i%2==0)
{
return i/2;
}
else
{
return (i-1)/2;
}
}
}
return 0;
}
void delete_tree(int tree[],int leaf)
{
int ptr,ptr1,ptr2;
ptr=search_parent(tree,leaf);
if(ptr==0)
{
printf("\nDeletion not possible!");
}
else
{
ptr1=ptr*2;
ptr2=ptr*2+1;
if(tree[ptr1]==leaf)
{
if((tree[ptr1*2]==0)&&(tree[ptr1*2+1]==0))
{
tree[ptr1]=0;
}
else
{
printf("\nDeletion not possible!");
}
}
if(tree[ptr2]==leaf)
{
if((tree[ptr2*2]==0)&&(tree[ptr2*2+1]==0))
{
tree[ptr2]=0;
}
else
{
printf("\nDeletion not possible!");
}
}
}
}
int main ()
{
int tree[100],i,j,item,parent,leaf,ch;
for(i=0;i<100;i++)
{
tree[i]=0;
}
printf("\nArray");
build_tree(tree,1);
tree_traversal(tree,1);
do
{
printf("\n\n..MENU..\n1. Insert an element.\n2. Delete a leaf.\n3. Traversal\n4. Exit\nEnter your choice: ");
scanf("%d",&ch);
switch(ch)
{
case 1: printf("\nEnter a parent node: ");
fflush(stdin);
scanf("%d",&parent);
insert_tree(tree,parent);
break;
case 2: printf("\nEnter a leaf node: ");
fflush(stdin);
scanf("%d",&leaf);
delete_tree(tree,leaf);
break;
case 3: tree_traversal(tree,1);
break;
case 4: exit(0);
default: printf("\nWrong choice");
}
}
while(1);
}

No comments

Powered by Blogger.