Friday, May 27, 2016

C program to make a binary tree and print the tree in inorder, preorder and postorder form

#include<stdio.h>
#include<stdlib.h>
struct node
{
 int info;
 struct node *left,*right;
}*root;
//function to create a new node in tree
node *create(struct node *ptr,int n)
 {
  struct node *curr;
  curr=(node *)malloc(sizeof(node));
  if(ptr==NULL)
   {
    curr->info=n;
    curr->left=NULL;
    curr->right=NULL;
    ptr=curr;
   }
  else
   {
    if(ptr->info>n)
     ptr->left=create(ptr->left,n);
    else
     ptr->right=create(ptr->right,n);
   }
   return ptr;
 }
void preorder(struct node *ptr)
 {
  if(ptr!=NULL)
   {
    printf(" %d",ptr->info);
    preorder(ptr->left);
    preorder(ptr->right);
   }
 }
void inorder(struct node *ptr)
{
 if(ptr!=NULL)
  {
   inorder(ptr->left);
   printf(" %d",ptr->info);
   inorder(ptr->right);
  }
}
void postorder(struct node *ptr)
 {
  if(ptr!=NULL)
   {
    postorder(ptr->left);
    postorder(ptr->right);
    printf(" %d",ptr->info);
   }
 }
void main()
{
//initially root will be null as there is no node
 root=NULL;
 int n;
 int i;
 do
  {
   printf("\n\n1.insert\n\n2.preorder.\n\n3.inorder\n\n4.postorder\n\n5.exit");
   scanf("%d",&n);
   if(n==1)
    {
     printf("Enter value to insert");
     scanf("%d",&i);
     root=create(root,i);
    }
   else if(n==2)
    {
     preorder(root);
    }
   else if(n==3)
    {
     inorder(root);
    }
   else if(n==4)
    {
     postorder(root);
    }
   }while(n!=5);
 }

output

1.insert
2.preorder
3.inorder
4.postorder
5.exit
1
Enter value to insert 4

1.insert
2.preorder
3.inorder
4.postorder
5.exit
1
Enter value to insert 3
1.insert
2.preorder
3.inorder
4.postorder
5.exit
2
3 4
1.insert
2.preorder
3.inorder
4.postorder
5.exit
5

No comments:

Post a Comment