Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <stdio.h>
- #include <stdlib.h>
- struct tree{
- int data;
- struct tree *left,*right;
- }*root = NULL;
- void insert(int val){
- struct tree *newNode = (struct tree*) malloc(sizeof(struct tree));
- newNode->data = val; newNode->right = newNode->left = NULL;
- if(!root) root = newNode;
- else{
- struct tree *help = root,*previous = NULL;
- while(help){//traversing to find insertion point
- previous = help;
- if(val < help->data) help = help ->left;
- else if(val > help->data) help = help->right;
- else{
- printf("\nDublicate values not allowed.\n");
- return;
- }
- }
- if(val > previous->data) previous->right = newNode;
- else previous->left = newNode;
- }
- }
- void inorder(struct tree* help){
- if(help){
- inorder(help->left);
- printf(" |%d| ", help->data);
- inorder(help->right);
- }
- if(!root) printf("The tree is empty.\n");
- }
- void preorder(struct tree* help){
- if(help){
- printf(" |%d| ", help->data);
- preorder(help->left);
- preorder(help->right);
- }
- if(!root) printf("The tree is empty.\n");
- }
- void postorder(struct tree* help){
- if(help){
- postorder(help->left);
- postorder(help->right);
- printf(" |%d| ", help->data);
- }
- if(!root) printf("The tree is empty.\n");
- }
- int main(){
- int n, choice;
- while(1){
- printf("\n\n1.Insert 2.Inorder 3.Preorder 4.Postorder 5.Exit: ");
- scanf("%d", &choice);
- switch(choice){
- case 1: printf("\nInsert: ");
- scanf("%d",&n);
- insert(n);
- break;
- case 2: printf("The tree by Inorder traversal is:-\n");
- inorder(root);
- break;
- case 3: printf("The tree by Prerder traversal is:-\n");
- preorder(root);
- break;
- case 4: printf("The tree by Postorder traversal is:-\n");
- postorder(root);
- break;
- case 5: return 0;
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement