Data Structures Practical 27
Question 1
Write a C program to construct the binary search tree from following data. Elements: [1, 5, 7, 8, 10, 12] and traverse in pre-order.
preorder.c
C
#include <stdio.h>
#include <conio.h>
#include <stdlib.h>
struct node
{
int data;
struct node *left;
struct node *right;
};
struct node* createNode(int value)
{
struct node *newNode = (struct node *)malloc(sizeof(struct node));
newNode->data = value;
newNode->left = NULL;
newNode->right = NULL;
return newNode;
}
struct node* insert(struct node *root, int value)
{
if (root == NULL)
return createNode(value);
if (value < root->data)
root->left = insert(root->left, value);
else if (value > root->data)
root->right = insert(root->right, value);
return root;
}
struct node* search(struct node* root, int key)
{
if (root == NULL || root->data == key)
return root;
if (key < root->data)
return search(root->left, key);
return search(root->right, key);
}
void preorder(struct node *root)
{
if (root != NULL) {
printf("%d ", root->data);
preorder(root->left);
preorder(root->right);
}
}
void main()
{
struct node *root = NULL;
int elements[] = {1, 5, 7, 8, 10, 12};
int n = 6;
int i;
clrscr();
printf("--- Constructing BST from Elements ---\n");
printf("Inserting sequence: 1, 5, 7, 8, 10, 12\n\n");
for (i = 0; i < n; i++)
root = insert(root, elements[i]);
printf("Pre-order Traversal Result:\n");
preorder(root);
printf("\n");
getch();
}
Output
Question 2
Write a C program to construct the binary search tree from following data. Elements: [1, 5, 7, 8, 10, 12] and traverse in post-order.
postorder.c
C
#include <stdio.h>
#include <conio.h>
#include <stdlib.h>
struct node
{
int data;
struct node *left;
struct node *right;
};
struct node* createNode(int value)
{
struct node *newNode = (struct node *)malloc(sizeof(struct node));
newNode->data = value;
newNode->left = NULL;
newNode->right = NULL;
return newNode;
}
struct node* insert(struct node *root, int value)
{
if (root == NULL)
return createNode(value);
if (value < root->data)
root->left = insert(root->left, value);
else if (value > root->data)
root->right = insert(root->right, value);
return root;
}
struct node* search(struct node* root, int key)
{
if (root == NULL || root->data == key)
return root;
if (key < root->data)
return search(root->left, key);
return search(root->right, key);
}
void postorder(struct node *root) {
if (root != NULL) {
postorder(root->left);
postorder(root->right);
printf("%d ", root->data);
}
}
void main()
{
struct node *root = NULL;
int elements[] = {1, 5, 7, 8, 10, 12};
int n = 6;
int i;
clrscr();
printf("--- Constructing BST from Elements ---\n");
printf("Inserting sequence: 1, 5, 7, 8, 10, 12\n\n");
for (i = 0; i < n; i++)
root = insert(root, elements[i]);
printf("Pre-order Traversal Result:\n");
postorder(root);
printf("\n");
getch();
}
Output
