Write the C code to print the post order traversal of a binary tree from its preorder and inorder traversal.
#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;
}
Comments
Leave a comment