For the given data construct Binary Search tree and obtain pre-order , post order and In-
order transversal ( Data set: -90,0,78,20,34,678,32,56,56).
#include <stdio.h>
#include <stdlib.h>
typedef struct Node_ {
int data;
struct Node_* left;
struct Node_* right;
} Node;
Node* add_node(Node* tree, int value) {
if (!tree) {
Node* new_node = (Node*) malloc(sizeof(Node));
new_node->left = new_node->right = NULL;
new_node->data = value;
return new_node;
}
if (value < tree->data) {
tree->left = add_node(tree->left, value);
}
else {
tree->right = add_node(tree->right, value);
}
return tree;
}
void free_tree(Node* tree) {
if (tree->left) {
free_tree(tree->left);
}
if (tree->right) {
free_tree(tree->right);
}
free(tree);
}
void print_preorder(Node* tree) {
printf("%d ", tree->data);
if (tree->left) {
print_preorder(tree->left);
}
if (tree->right) {
print_preorder(tree->right);
}
}
void print_postorder(Node* tree) {
if (tree->left) {
print_postorder(tree->left);
}
if (tree->right) {
print_postorder(tree->right);
}
printf("%d ", tree->data);
}
void print_inorder(Node* tree) {
if (tree->left) {
print_inorder(tree->left);
}
printf("%d ", tree->data);
if (tree->right) {
print_inorder(tree->right);
}
}
int main() {
Node* tree=NULL;
int data[] = {-90,0,78,20,34,678,32,56,56};
int n = sizeof(data) /sizeof(data[0]);
int i;
for (i=0; i<n; i++) {
tree = add_node(tree, data[i]);
}
printf("Preorder:\n");
print_preorder(tree);
printf("\n\nPostorder:\n");
print_postorder(tree);
printf("\n\nInorder:\n");
print_inorder(tree);
free_tree(tree);
return 0;
}
Preorder:
-90 0 78 20 34 32 56 56 678
Postorder:
32 56 56 34 20 678 78 0 -90
Inorder:
-90 0 20 32 34 56 56 78 678
Comments
Leave a comment