Abinayashri S
Write a C program that use recursive functions to traverse the given binary tree in
Inorder.
program:
#include <stdio.h>
#include <stdlib.h>
typedef struct Node {
int data;
struct Node* left;
struct Node* right;
} Node;
Node* createNode(int data) {
Node* newNode = malloc(sizeof(Node));
newNode->data = data;
newNode->left = newNode->right = NULL;
return newNode;
}
void inorderTraversal(Node* root) {
if (root == NULL)
return;
inorderTraversal(root->left);
printf("%d ", root->data);
inorderTraversal(root->right);
}
int main() {
Node* root = createNode(1);
root->left = createNode(2);
root->right = createNode(3);
root->left->left = createNode(4);
root->left->right = createNode(5);
int choice;
while (1) {
printf("\nBinary Tree Traversal:\n");
printf("1. Inorder Traversal\n");
printf("2. Exit\n");
printf("Enter your choice: ");
scanf("%d", &choice);
if (choice == 1) {
printf("Inorder Traversal: ");
inorderTraversal(root);
printf("\n");
} else if (choice == 2) {
printf("Exiting...\n");
break;
} else {
printf("Invalid choice. Please try again.\n");
}
}
return 0;
}
output:
Binary Tree Traversal:
1. Inorder Traversal
2. Exit
Enter your choice: 1
Inorder Traversal: 4 2 5 1 3
Binary Tree Traversal:
1. Inorder Traversal
2. Exit
Enter your choice: 2
Exiting..