Write a program to implement binary tree and perform various traversal of it.
Sample input: (the first line contains the n-->number of nodes in the binary tree followed by n values)
7
1
2
3
4
5
6
7
Sample Output:
Inorder traversal
6 4 2 1 3 5 7
Preorder traversal
1 2 4 6 3 5 7
Postorder traversal
6 4 2 7 5 3 1
code👇👇👇👇👇👇👇👇👇👇👇👇👇👇
#include<stdio.h>
#include<stdlib.h>
struct node{
int info;
struct node *lchild;
struct node *rchild;
}*root;
typedef struct node NODE;
int count=1;
NODE* insert(NODE *p, int item){
if (p==NULL){
p=(NODE*)malloc(sizeof(NODE));
p->lchild = NULL;
p->rchild=NULL;
p->info=item;
count++;
}
else {
if(count%2==0)
p->lchild=insert(p->lchild,item);
else
p->rchild=insert (p->rchild,item);
}
return(p);
}
void preorder(struct node *ptr){
if (root==NULL){
printf("Tree is Empty");
return;
}
if(ptr!=NULL){
printf("%d ",ptr->info);
preorder(ptr->lchild);
preorder(ptr->rchild);
}
}
void inorder (struct node *ptr)
{
if(root==NULL){
printf("Tree is Empty");
return;
}
if(ptr!=NULL){
inorder(ptr->lchild);
printf("%d ",ptr->info);
inorder(ptr->rchild);
}
}
void postorder(struct node *ptr){
if(root==NULL){
printf("Tree is Empty");
return;
}
if(ptr!=NULL)
{
postorder(ptr->lchild);
postorder(ptr->rchild);
printf("%d ",ptr->info);
}
}
int main(){
int n,i,item;
root=NULL;
scanf("%d",&n);
for(i=0;i<n;i++){
scanf("%d",&item);
root=insert(root,item);
}
printf("\n Inorder traversal\n");
inorder(root);
printf("\n Preorder traversal\n");
preorder(root);
printf("\n Postorder traversal\n");
postorder(root);
}
No comments:
Post a Comment