Tree Traversal, In-order, Pre-order, Post-order

/*
BST: Binary SeaRCh Tree, LC: Left Child, RC: Right Child, TN: Temp Node, POT: Pre-Order Traversal,IOT: In-Order Traversal,PST: Post-Order Traversal,
*/
#include <stdio.h>
#include <stdlib.h>
struct node {
   int data;
   struct node *LC;
   struct node *RC;
};
struct node *root = NULL;
void insert(int data) {
   struct node *TN = (struct node*) malloc(sizeof(struct node));
   struct node *current;
   struct node *parent;
   TN->data = data;
   TN->LC = NULL;
   TN->RC = NULL;
   if(root == NULL) { //if tree is empty
      root = TN;
   } else {
      current = root;
      parent = NULL;
      while(1) {
         parent = current;
         if(data < parent->data) {//go to left of the tree
            current = current->LC;
            if(current == NULL) {//insert to the left
               parent->LC = TN;
               return;
            }
         }  //go to right of the tree
         else {
            current = current->RC;
            if(current == NULL) {//insert to the right
               parent->RC = TN;
               return;
            }
         }
      }
   }
}
void POT(struct node* root) {
   if(root != NULL) {
      printf(“%d “,root->data);
      POT(root->LC);
      POT(root->RC);
   }
}
void IOT(struct node* root) {
   if(root != NULL) {
      IOT(root->LC);
      printf(“%d “,root->data);
      IOT(root->RC);
   }
}
void PST(struct node* root) {
   if(root != NULL) {
      PST(root->LC);
      PST(root->RC);
      printf(“%d “, root->data);
   }
}
int main() {
   int x;
   printf(“Enter tree nodes, -1 for exit.”);
   scanf(“%d”,&x);
   while(x != -1){
insert(x);
scanf(“%d”,&x);
   }
   printf(“\nPreorder traversal: “);
   POT(root);
   printf(“\nInorder traversal: “);
   IOT(root);
   printf(“\nPost order traversal: “);
   PST(root);
   return 0;
}

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes:

<a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong>