C program to create a binary search tree and perform inoreder, preorder and postorder traversal.
#include<stdio.h>#include<conio.h>#include<malloc.h>struct node{struct node *left;struct node *right;int data;};void insert(struct node **,int);void inorder(struct node *);void postorder(struct node *);void preorder(struct node *);void main(){struct node *bt;bt=NULL;int req,i=1,num;clrscr();printf("enter the no of nodes to be inserted\n");scanf("%d",&req);while(i++<=req){printf("enter data\n");scanf("%d",&num);insert(&bt,num);}printf("inorder ...\n");inorder(bt);printf("postorder ....\n");postorder(bt);printf("preoder ....\n");preorder(bt);getch();}void insert(struct node **temp,int num){if(*temp==NULL){*temp=(struct node*)malloc(sizeof(struct node));(*temp)->left=NULL;(*temp)->data=num;(*temp)->right=NULL;return;}else{if(num < (*temp)->data)insert(&((*temp)->left),num);if(num > (*temp)->data)insert(&((*temp)->right),num);}return;}void inorder(struct node *temp){if(temp!=NULL){inorder(temp->left);printf("%d\n",temp->data);inorder(temp->right);}else return;}void postorder(struct node *temp){if(temp!=NULL){postorder(temp->left);postorder(temp->right);printf("%d\n",(*temp).data);}else return;}void preorder(struct node *temp){if(temp!=NULL){printf("%d\n",(*temp).data);preorder((*temp).left);preorder((*temp).right);
}else return;}
No comments:
Post a Comment