tree implementation
in c
#include<stdio.h>
#include<malloc.h>
void insert(int);
void traverse();
struct node
{
int data;
struct node *left;
struct node *right;
};
struct node *root;
int main()
{
root=NULL;
insert('B');
insert(10);
insert(5);
insert(15);
insert(12);
insert(2);
traverse();
return 0;
}
void insert(int d)
{
struct node
*newnode=(struct node *)malloc(sizeof(struct node));
newnode->data=d;
newnode->left=NULL;
newnode->right=NULL;
struct node
*ptr=root;
if(root==NULL)
{
root=newnode;
//newnode->left=NULL;
//newnode->right=NULL;
}
else
{
while(ptr!=NULL)
{
if(d<ptr->data)
{
if(ptr->left==NULL)
{
ptr->left=newnode;
ptr=NULL;
}
else
{
ptr=ptr->left;
}
}
else
{
//if(d>ptr->data)
//{
if(ptr->right==NULL)
{
ptr->right=newnode;
ptr=NULL;
}
else
{
ptr=ptr->right;
}
}
}
}//else first ends
}//insert ends
void inorder(struct
node *ptr);
void preorder(struct
node *ptr);
void
postorder(struct node *ptr);
void traverse()
{
printf("\nInorder\n");
inorder(root);
printf("\nPre
order\n");
preorder(root);
printf("\nPost
Order\n");
postorder(root);
printf("\n\n");
}//traverse ends
here
void inorder(struct
node *ptr)
{
if(ptr!=NULL)
{
inorder(ptr->left);
printf("%d
",ptr->data);
inorder(ptr->right);
}
}
void preorder(struct
node *ptr)
{
if(ptr!=NULL)
{
printf("%d
",ptr->data);
preorder(ptr->left);
preorder(ptr->right);
}
}
void
postorder(struct node *ptr)
{
if(ptr!=NULL)
{
postorder(ptr->left);
postorder(ptr->right);
printf("%d
",ptr->data);
}
}
/*
Inorder
2 5 10 12 15 66
Pre order
66 10 5 2 15 12
Post Order
2 5 12 15 10 66
*/
No comments:
Post a Comment