You are on page 1of 4

#include <stdio.

h>
#include <stdlib.h>

struct node
{
int key;
struct node *left, *right;
};

struct node* newNode(int);


void inorder(struct node *);
void preorder(struct node *);
struct node* insert(struct node *, int );

struct node* newNode(int item)


{
struct node* temp = (struct node*)malloc(sizeof(struct node));
temp->key = item;
temp->left=temp->right=NULL;
return temp;
}

void inorder(struct node* root)


{
int top=0;
struct node *stack[100];
stack[0]=NULL;

struct node *ptr=root;


while(ptr!=NULL || top!=0)
{
if(ptr!=NULL)
{
top=top+1;
stack[top]=ptr;
ptr=ptr->left;
}
else
{
ptr=stack[top];
top=top-1;
printf("%d ",ptr->key);
ptr=ptr->right;
}

}
}

void preorder(struct node *root)


{
int top=0;
struct node *stack[100];
stack[0]=NULL;

struct node *ptr=root;


while(ptr!=NULL)
{
printf("%d ",ptr->key);
if(ptr->right!=NULL)
{
top=top+1;
stack[top]=ptr->right;
}
if(ptr->left!=NULL)
ptr=ptr->left;
else
{
ptr=stack[top];
top=top-1;
}

struct node* insert(struct node* ROOT, int item)


{
struct node *ptr=ROOT;
int fl=0;
struct node *ptr1;

while(ptr!=NULL && fl==0)


{
if(item < ptr->key)
{
ptr1=ptr;
ptr=ptr->left;
}
else if(item > ptr->key)
{
ptr1=ptr;
ptr=ptr->right;
}
else
{
fl=1;
printf("\n Item already exists \n");
break;
}

}
struct node *new=newNode(item);

if(ROOT == NULL)
{
ROOT=new;
return ROOT;
}

if(ptr1->key<item)
ptr1->right=new;
else
ptr1->left=new;

return ROOT;
}

int main()
{

struct node* root =NULL;


int data,t;
do
{
printf("Enter root of the tree \n");
scanf("%d",&data);
root= insert(root,data);
printf("Enter data or not t= ");
scanf("%d",&t);

}while(t!=0);

printf(" Inorder traversal of the tree is \n");


inorder(root);
printf("\n");
printf("preorder traversal of the tree is \n");
preorder(root);

return 0;

You might also like