Traverse

#include<stdio.h>
#include<process.h>
#include<malloc.h>
typedef struct binarytree
{
struct binarytree *lp;
int key;
struct binarytree *rp;
}NODE;
NODE* insert(NODE *,int);
void inorder(NODE *);
void preorder(NODE *);
void postorder(NODE *);
void main()
{
int choice,value,flag=1;
NODE *root=NULL;
while(flag)
{
printf(“\n\tEnter 1 to insert the node in tree”);
printf(“\n\tEnter 2 to traverse in inorder”);
printf(“\n\tEnter 3 to traverse in preorder”);
printf(“\n\tEnter 4 to traverse in postorder”);
printf(“\n\tEnter 5 to exit”);
printf(“\n\n\tEnter your choice:”);
scanf(“%d”,&choice);
switch(choice)
{
case 1:
printf(“Enter the value of the node:”);
scanf(“%d”,&value);
root=insert(root,value);
break;
case 2:
printf(“\n\tAddress\t\tValue\t\tLeft\t\tRight\n”);
printf(“___________________________________________________________________________________________\n”);
inorder(root);
break;
case 3:
printf(“\n\tAddress\t\tValue\t\tLeft\t\tRight\n”);
printf(“___________________________________________________________________________________________\n”);
preorder(root);
break;
case 4:
printf(“\n\tAddress\t\tValue\t\tLeft\t\tRight\n”);
printf(“___________________________________________________________________________________________\n”);
postorder(root);
break;
case 5:
abort();
default:
printf(“Invalid Selection\n\n”);

}

}
}
NODE* insert(NODE *root,int value)
{
if(root==NULL)
{
NODE *newnode=(NODE *)malloc(sizeof(NODE));
newnode->lp=NULL;
newnode->key=value;
newnode->rp=NULL;
return newnode;
}
else
{
if(value>root->key)
root->rp=insert(root->rp,value);
else
root->lp=insert(root->lp,value);
}
return root;
}
void inorder(NODE *root)
{
if(root==NULL)
return;
else
{
if(root->lp != NULL)
inorder(root->lp);

printf(“\t%u\t\t%d\t\t%u\t\t%u\n”,root,root->key,root->lp,root->rp);

if(root->rp != NULL)
inorder(root->rp);
}
exit;
}
void preorder(NODE *root)
{
if(root==NULL)
return;
else
{
printf(“\t%u\t\t%d\t\t%u\t\t%u\n”,root,root->key,root->lp,root->rp);
if(root->lp != NULL)
preorder(root->lp);

if(root->rp != NULL)
preorder(root->rp);
}
exit;
}
void postorder(NODE *root)
{
if(root==NULL)
return;
else
{

if(root->lp != NULL)
postorder(root->lp);

if(root->rp != NULL)
postorder(root->rp);
printf(“\t%u\t\t%d\t\t%u\t\t%u\n”,root,root->key,root->lp,root->rp);
}
exit;
}

Share

About the Author

Akash Padhiyar

Visit Website

There are no comments yet, add one below.

Leave a Comment

Your email address will not be published. Required fields are marked *

*

Time limit is exhausted. Please reload CAPTCHA.