Skip to content

Instantly share code, notes, and snippets.

@B45i
Last active April 18, 2016 04:57
Show Gist options
  • Save B45i/6a28cfff2563bb07c5593ec74d4a85a3 to your computer and use it in GitHub Desktop.
Save B45i/6a28cfff2563bb07c5593ec74d4a85a3 to your computer and use it in GitHub Desktop.
#include <stdio.h>
#include <stdlib.h>
void menu(void);
struct node{
int i;
struct node *lc;
struct node *rc;
}*root;
void buildtree(struct node *ptr){
struct node *lcptr,*rcptr;
int c;
if(ptr != NULL){
printf("Enter item : ");
scanf("%d",&ptr->i);
printf("Does %d has a Left child ? (1/0) : ",ptr->i);
scanf("%d",&c);
if(c==1){
lcptr = (struct node *)malloc(sizeof(struct node));
ptr->lc = lcptr;
buildtree(lcptr);
}
else{
lcptr = NULL;
ptr->lc = NULL;
buildtree(lcptr);
}
printf("Does %d has a right child ? (1/0) : ",ptr->i);
scanf("%d",&c);
if(c==1){
rcptr = (struct node *)malloc(sizeof(struct node));
ptr->rc = rcptr;
buildtree(rcptr);
}
else{
rcptr = NULL;
ptr->rc = NULL;
buildtree(rcptr);
}
}
}
void preorder(struct node *ptr){
if(ptr !=NULL){
printf("%d ",ptr->i);
preorder(ptr->lc);
preorder(ptr->rc);
}
}
void inorder(struct node *ptr){
if(ptr !=NULL){
inorder(ptr->lc);
printf("%d ",ptr->i);
inorder(ptr->rc);
}
}
void postorder(struct node *ptr){
if(ptr !=NULL){
postorder(ptr->lc);
postorder(ptr->rc);
printf("%d ",ptr->i);
}
}
void display(struct node *ptr,int l){
int i;
if(ptr != NULL){
display(ptr->rc,l+5);
for(i=0;i<l;i++){
printf(" ");
}
printf("%d\n",ptr->i);
display(ptr->lc,l+5);
}
}
void search(struct node *ptr,int item){
if(ptr->lc != NULL||ptr->rc != NULL){
if((ptr->lc->i==item)||(ptr->rc->i==item)){
printf("\nItem found as child of %d",ptr->i);
return ;
}
else{
search(ptr->lc,item);
search(ptr->rc,item);
}
printf("\nItem not found");
}
}
void submenu(void){
int op,item;
printf("\n1 for Search\n2 for Preordern\n3 for Inorder\n4 for Postorder\n5 for Main Menu");
printf("\nEnter Choice : ");
scanf("%d",&op);
switch(op){
case 1:
printf("\nEnter item: ");
scanf("%d",&item);
search(root,item);
submenu();
break;
case 2:
preorder(root);
printf("\n");
submenu();
break;
case 3:
inorder(root);
printf("\n");
submenu();
break;
case 4:
postorder(root);
printf("\n");
submenu();
break;
case 5:
menu();
break;
default:
printf("\nInvalid option");
break;
}
}
void menu(void){
int op;
printf("\nPress 1 for BUILD TREE\nPress 2 for display\nPress 3 to EXIT");
printf("\nEnter Choice: ");
scanf("%d",&op);
switch(op){
case 1:
if(root==NULL){
root = (struct node*)malloc(sizeof(struct node));
buildtree(root);
}
submenu();
menu();
break;
case 2:
display(root,0);
break;
case 3:
return ;
break;
default:
printf("\nInvalid Option");
menu();
}
}
int main(){
menu();
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment