Tuesday 19 May 2015

C program to create tree and implement tree traversal technique (in-order , post-order and pre-order )

#include<stdio.h>

#include<stdlib.h>

#include<string.h>

struct node

{

int data;

struct node *llink,*rlink;

};

typedef struct node * NODE;

NODE insert(NODE root)

{

NODE tmp,cur,pre;

char direction[20];

int item,i;

tmp=(NODE)malloc(sizeof(struct node));

printf("Enter the item to insert: ");

scanf("%d",&item);

tmp­>data=item;

tmp­>llink=NULL;

tmp­>rlink=NULL;

if(root==NULL)

{

printf("Node inserted to tree!\n");

return(tmp);

}

printf("Enter the direction: ");

scanf("%s",&direction);

toupper(direction);

pre=NULL;

cur=root;

for(i=0;i<strlen(direction);i++)

{

if(cur==NULL)

break;

pre=cur;

if(direction[i]=='L')

cur=cur­>llink;

else

cur=cur­>rlink;

}

if(cur!=NULL || i < strlen(direction))

{

printf("Enter the proper direction!!!\n");

free(tmp);

return(root);

}

if(direction[i­1]=='L')

{

pre­>llink=tmp;

printf("Node inserted to tree!\n");

}

else

{

pre­>rlink=tmp;

printf("Node inserted to tree!\n");

}

return(root);

}

void inorder(NODE root)

{

if(root==NULL)

inorder(root­>llink);

printf("%d ",root­>data);

inorder(root­>rlink);

}

void preorder(NODE root)

{

if(root==NULL)

printf("%d ",root­>data);

preorder(root­>llink);

preorder(root­>rlink);

}

void postorder(NODE root)

{

if(root==NULL)

postrder(root­>llink);

return;

return;

return;

postder(root­>rlink);

printf("%d ",root­>data);

}

void main()

{

NODE root=NULL;

int ch;

while(1)

{

printf("*******Binary­Search­Traversing*********\n");

printf("1. Insert Node\n2. Inorder\n3. Preorder\n4. Postorder\n5. Exit\n");

printf("Enter your choice: ");

scanf("%d",&ch);

switch(ch)

{

case 1: root=insert(root);

break;

case 2: inorder(root);

printf("\n");

break;

case 3: preorder(root);

printf("\n");

break;

case 4: postorder(root);

printf("\n");

break;

case 5: exit(0);

default: printf("Enter the valid menu option!!\n");

}

}

}

No comments:

Post a Comment