Abinayashri S
Write a C program that use recursive functions to traverse the given binary tree in
preorder
program:
#include <stdio.h>
#include <stdlib.h>
struct Node {
int data;
struct Node* left;
struct Node* right;
};
struct Node* createNode(int data) {
struct Node* newNode = malloc(sizeof(struct Node));
newNode->data = data;
newNode->left = NULL;
newNode->right = NULL;
return newNode;
}
void preorderTraversal(struct Node* root) {
if (root == NULL)
return;
printf("%d ", root->data);
preorderTraversal(root->left);
preorderTraversal(root->right);
}
struct Node* buildBinaryTree() {
struct Node* root = NULL;
int data;
printf("Enter the data for the root node (Enter -1 to exit): ");
scanf("%d", &data);
if (data != -1) {
root = createNode(data);
printf("Enter the left child of %d:\n", data);
root->left = buildBinaryTree();
printf("Enter the right child of %d:\n", data);
root->right = buildBinaryTree();
}
return root;
}
void displayMenu() {
printf("\nBinary Tree Traversal:\n");
printf("1. Build Binary Tree\n");
printf("2. Preorder Traversal\n");
printf("3. Exit\n");
printf("Enter your choice: ");
}
int main() {
struct Node* root = NULL;
int choice;
do {
displayMenu();
scanf("%d", &choice);
switch (choice) {
case 1:
printf("Building Binary Tree:\n");
if (root != NULL) {
printf("Binary Tree already exists. Rebuilding...\n");
free(root);
}
root = buildBinaryTree();
break;
case 2:
if (root == NULL) {
printf("Binary Tree is empty. Please build the tree first.\n");
} else {
printf("Preorder Traversal: ");
preorderTraversal(root);
printf("\n");
}
break;
case 3:
printf("Exiting...\n");
if (root != NULL) {
free(root);
}
break;
default:
printf("Invalid choice. Please try again.\n");
}
} while (choice != 3);
return 0;
}
output:
Binary Tree Traversal:
1. Build Binary Tree
2. Preorder Traversal
3. Exit
Enter your choice: 1
Building Binary Tree:
Enter the data for the root node (Enter -1 to exit): 1
Enter the left child of 1:
Enter the data for the root node (Enter -1 to exit): 2
Enter the left child of 2:
Enter the data for the root node (Enter -1 to exit): 4
Enter the left child of 4:
Enter the data for the root node (Enter -1 to exit): -1
Enter the right child of 4:
Enter the data for the root node (Enter -1 to exit): -1
Enter the right child of 2:
Enter the data for the root node (Enter -1 to exit): 5
Enter the left child of 5:
Enter the data for the root node (Enter -1 to exit): -1
Enter the right child of 5:
Enter the data for the root node (Enter -1 to exit): -1
Enter the right child of 1:
Enter the data for the root node (Enter -1 to exit): 3
Enter the left child of 3:
Enter the data for the root node (Enter -1 to exit): -1
Enter the right child of 3:
Enter the data for the root node (Enter -1 to exit): -1
Binary Tree Traversal:
1. Build Binary Tree
2. Preorder Traversal
3. Exit
Enter your choice: 2
Preorder Traversal: 1 2 4 5 3
Binary Tree Traversal:
1. Build Binary Tree
2. Preorder Traversal
3. Exit
Enter your choice: 3
Exiting..