Answer to Question #270184 in C for Amit

Question #270184

Write the C code to print the post order traversal of a binary tree from its preorder and inorder traversal.


1
Expert's answer
2021-11-23T05:18:35-0500
#include <stdio.h>
#include <stdlib.h>


struct BinaryTree {
   int item; 
	
   struct BinaryTree *leftTree;
   struct BinaryTree *rightTree;
};


struct BinaryTree *head = NULL;


void insert(int data) {
   struct BinaryTree *temp = (struct BinaryTree*) malloc(sizeof(struct BinaryTree));
   struct BinaryTree *currentTree;
   struct BinaryTree *parentTree;


   temp->item = data;
   temp->leftTree = NULL;
   temp->rightTree = NULL;


   
   if(head == NULL) {
      head = temp;
   } else {
      currentTree = head;
      parentTree = NULL;


      while(1) { 
         parentTree = currentTree;
         
        
         if(data < parentTree->item) {
            currentTree = currentTree->leftTree;                
            
           
            if(currentTree == NULL) {
               parentTree->leftTree = temp;
               return;
            }
         }  
         else {
            currentTree = currentTree->rightTree;


            
            if(currentTree == NULL) {
               parentTree->rightTree = temp;
               return;
            }
         }
      }            
   }
}


struct BinaryTree* search(int data) {
   struct BinaryTree *currentTree = head;
   printf("Traversing elements: ");


   while(currentTree->item != data) {
      if(currentTree != NULL)
         printf("%d ",currentTree->item); 


      
      if(currentTree->item > data) {
         currentTree = currentTree->leftTree;
      }
     
      else {                
         currentTree = currentTree->rightTree;
      }


      
      if(currentTree == NULL) {
         return NULL;
      }
   }
   
   return currentTree;
}


void preorder(struct BinaryTree* head) {
   if(head != NULL) {
      printf("%d ",head->item);
      preorder(head->leftTree);
      preorder(head->rightTree);
   }
}


void inorder(struct BinaryTree* head) {
   if(head != NULL) {
      inorder(head->leftTree);
      printf("%d ",head->item);          
      inorder(head->rightTree);
   }
}


void postorder(struct BinaryTree* root) {
   if(root != NULL) {
      postorder(root->leftTree);
      postorder(root->rightTree);
      printf("%d ", root->item);
   }
}


int main() {
   int i;
   int array[7] = { 27, 14, 35, 10, 19, 31, 42 };


   for(i = 0; i < 7; i++)
      insert(array[i]);


   i = 31;
   struct BinaryTree * temp = search(i);


   if(temp != NULL) {
      printf("[%d] Element found.", temp->item);
      printf("\n");
   }else {
      printf("[ x ] Element not found (%d).\n", i);
   }




   return 0;
}

Need a fast expert's response?

Submit order

and get a quick answer at the best price

for any assignment or question with DETAILED EXPLANATIONS!

Comments

No comments. Be the first!

Leave a comment

LATEST TUTORIALS
New on Blog
APPROVED BY CLIENTS