the following program uses recursion to input nodes and also displays inorder preorder and postorder forms in the output .
Procedure of insertion is simple first input a node and then ask the user whether the tree has left and right child
if yes call the function again with pointer to left or right child of the inserted node.
Procedure of insertion is simple first input a node and then ask the user whether the tree has left and right child
if yes call the function again with pointer to left or right child of the inserted node.
OUTPUT come LIKE this :
C program :
#include<stdio.h>
#include<malloc.h>
typedef struct node { /* this typedef removes the hazzle of writing struct node instead
of node everytime we need to create a node (not required in c++ ) */
int data;
struct node *left,*right;
} node ;
int n,i=0;
node *insert(node *temp)
{ int e;
char ch;
temp=(node *)malloc(sizeof(node));
printf("\n Enter node ");
scanf("%d",&e);
i++;
temp->data=e;
temp->left=NULL;
temp->right=NULL;
if(i>=n)
return temp;
printf("\n does %d have left child (Y/N) :",temp->data);
getchar();
scanf("%c",&ch);
if(ch=='y'||ch=='Y')
temp->left=insert(temp->left);
printf("\n does %d have right child (Y/N) :",temp->data);
getchar();
scanf("%c",&ch);
if(ch=='y'||ch=='Y')
temp->right=insert(temp->right);
return temp;
}
void inorder(node *t)
{
if(t!=NULL)
{ inorder(t->left);
printf(" %d ",t->data);
inorder(t->right);
}
}
void preorder(node *t)
{
if(t!=NULL)
{ printf(" %d ",t->data);
preorder(t->left);
preorder(t->right);
}
}
void postorder(node *t)
{
if(t!=NULL)
{ preorder(t->left);
preorder(t->right);
printf(" %d ",t->data);
}
}
main()
{
node *root;
printf("\n simple Binary tree :(http://beginer2cs.blogspot.in) :\n");
printf("\n Enter Max number of nodes ");
scanf("%d",&n);
root=insert(root);
printf("\n Tree : Inorder :");
inorder(root);
printf("\n Tree : Preorder :");
preorder(root);
printf("\n Tree : Postorder :");
postorder(root);
}
No comments:
Post a Comment
THANKS FOR UR GREAT COMMENT