RSS

Tree Traversal

08 Mar

C Program for traversing a tree in Preorder, Postorder and Inorder:

 

#include<stdio.h>
#include<conio.h>
#include<malloc.h>
#include<process.h>
struct node
{
int num;
struct node *left;
struct node *right;
};
typedef struct node node;
node *root=NULL;
node *insert(struct node *tree, long num);
void preorder(node *tree);
int select();
void inorder(node *tree);
void postorder(node *tree);
int count=1;
void main()
{
int choice;
long digit;
do
{
choice=select();
switch(choice)
{
case 1:puts(“enter integer : to quit enter 0”);
if(digit!=0)
{
scanf(“%d”,&digit);
root=insert(root,digit);
}
continue;
case 2:puts(“\n preorder traversing tree”);
preorder(root);
continue;
case 3:puts(“\n inorder traversing tree”);
inorder(root);
continue;
case 4:puts(“\n postorder traversing tree”);
postorder(root);
continue;
case 5:puts(“end”);
exit(0);
}
}
while(choice !=5);
}
int select()
{
int selection;
do
{
puts(“\n enter 1:insert a node in the BT”);
puts(“\n enter 2:display(preorder) the BT”);
puts(“\n enter 3:display(inorder) the BT”);
puts(“\n enter 4:display(postorder) the BT”);
puts(“enter your choice”);
scanf(“%d”,&selection);
if((selection<1)||(selection>5))
{
puts(“wrong choice:try again”);
getch();
}
}
while((selection<1)||(selection>5));
return(selection);
}
node *insert(node *p,long digit)
{
if(p==NULL)
{
p=(node *)malloc(sizeof(node));
p->left=p->right=NULL;
p->num=digit;
count++;
}
else
if(count %2==0)
p->left=insert(p->left,digit);
else
p->right=insert(p->right,digit);
return(p);
}
void preorder(node *p)
{
if(p!=NULL)
{
printf(“%d\n”,p->num);
preorder(p->left);
preorder(p->right);
}
}
void inorder(node *p)
{
if(p!=NULL)
{
inorder(p->left);
printf(“%d\n”,p->num);
inorder(p->right);
}
}
void postorder(node *p)
{
if(p!=NULL)
{
postorder(p->left);
postorder(p->right);
printf(“\n%d”,p->num);
}
}
Advertisements
 
Leave a comment

Posted by on March 8, 2011 in C/C++

 

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

 
%d bloggers like this: