Tree Traversal Program
#include <stdio.h>
#include <stdlib.h>
struct node {
int data;
struct node* left;
struct node* right;
};
struct node* root = NULL;
void create();
void insert(struct node*, struct node*);
void inorder(struct node*);
void preorder(struct node*);
void postorder(struct node*);
void create() {
int data;
struct node* newnode = (struct node*)malloc(sizeof(struct node));
if (newnode == NULL) {
printf("Memory allocation failed.\n");
return;
printf("Enter the data: ");
scanf("%d", &data);
newnode->data = data;
newnode->left = NULL;
newnode->right = NULL;
if (root == NULL) {
root = newnode;
} else {
insert(root, newnode);
void insert(struct node* root, struct node* newnode) {
char ch;
printf("Do you want to add as left child (l) or right child (r)? ");
while ((getchar()) != '\n'); // clear the input buffer
scanf("%c", &ch);
switch (ch) {
case 'l':
case 'L':
if (root->left == NULL) {
root->left = newnode;
} else {
insert(root->left, newnode);
break;
case 'r':
case 'R':
if (root->right == NULL) {
root->right = newnode;
} else {
insert(root->right, newnode);
}
break;
default:
printf("Invalid choice. Node not inserted.\n");
free(newnode);
void inorder(struct node* root) {
if (root != NULL) {
inorder(root->left);
printf("%d ", root->data);
inorder(root->right);
void preorder(struct node* root) {
if (root != NULL) {
printf("%d ", root->data);
preorder(root->left);
preorder(root->right);
void postorder(struct node* root) {
if (root != NULL) {
postorder(root->left);
postorder(root->right);
printf("%d ", root->data);
}
int main() {
int choice;
printf("1. Create and insert\n2. Inorder\n3. Preorder\n4. Postorder\n5. Exit\n");
while (1) {
printf("Enter choice: ");
scanf("%d", &choice);
switch (choice) {
case 1:
create();
break;
case 2:
printf("Inorder traversal: ");
inorder(root);
printf("\n");
break;
case 3:
printf("Preorder traversal: ");
preorder(root);
printf("\n");
break;
case 4:
printf("Postorder traversal: ");
postorder(root);
printf("\n");
break;
case 5:
exit(0);
default:
printf("Invalid choice.\n");
return 0;