Advertisement
Shailrshah

Inorder, Preorder and Postorder Tree Traversals

Nov 13th, 2013
166
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 2.17 KB | None | 0 0
  1. #include <stdio.h>
  2. #include <stdlib.h>
  3. struct tree{
  4.     int data;
  5.     struct tree *left,*right;
  6. }*root = NULL;
  7. void insert(int val){
  8.     struct tree *newNode = (struct tree*) malloc(sizeof(struct tree));
  9.     newNode->data = val; newNode->right = newNode->left = NULL;
  10.     if(!root) root = newNode;
  11.     else{
  12.         struct tree *help = root,*previous = NULL;
  13.         while(help){//traversing to find insertion point
  14.             previous = help;
  15.             if(val < help->data) help = help ->left;
  16.             else if(val > help->data) help = help->right;
  17.             else{
  18.                 printf("\nDublicate values not allowed.\n");
  19.                 return;
  20.             }
  21.         }
  22.         if(val > previous->data)   previous->right = newNode;
  23.         else    previous->left = newNode;
  24.     }
  25. }
  26. void inorder(struct tree* help){
  27.     if(help){
  28.         inorder(help->left);
  29.         printf(" |%d| ", help->data);
  30.         inorder(help->right);
  31.     }
  32.     if(!root)   printf("The tree is empty.\n");
  33. }
  34. void preorder(struct tree* help){
  35.     if(help){
  36.         printf(" |%d| ", help->data);
  37.         preorder(help->left);
  38.         preorder(help->right);
  39.     }
  40.     if(!root)   printf("The tree is empty.\n");
  41. }
  42. void postorder(struct tree* help){
  43.     if(help){
  44.         postorder(help->left);
  45.         postorder(help->right);
  46.         printf(" |%d| ", help->data);
  47.     }
  48.     if(!root)   printf("The tree is empty.\n");
  49. }
  50. int main(){
  51.     int n, choice;
  52.     while(1){
  53.         printf("\n\n1.Insert 2.Inorder 3.Preorder 4.Postorder 5.Exit: ");
  54.         scanf("%d", &choice);
  55.         switch(choice){
  56.             case 1: printf("\nInsert: ");
  57.                     scanf("%d",&n);
  58.                     insert(n);
  59.                     break;
  60.             case 2: printf("The tree by Inorder traversal is:-\n");
  61.                     inorder(root);
  62.                     break;
  63.             case 3: printf("The tree by Prerder traversal is:-\n");
  64.                     preorder(root);
  65.                     break;
  66.             case 4: printf("The tree by Postorder traversal is:-\n");
  67.                     postorder(root);
  68.                     break;
  69.             case 5: return 0;
  70.         }
  71.     }
  72. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement