Write C programs to implement create and display operation for binary tree.
#include <stdio.h>
#include <stdlib.h>
// Structure of a binary tree node
struct Node {
int data;
struct Node* left;
struct Node* right;
};
// Function to create a new node
struct Node* createNode(int data) {
struct Node* newNode = (struct Node*)malloc(sizeof(struct Node));
newNode->data = data;
newNode->left = NULL;
newNode->right = NULL;
return newNode;
}
// Function to create the binary tree recursively
struct Node* createTree() {
int data;
printf("Enter data (-1 for no node): ");
scanf("%d", &data);
if (data == -1)
return NULL;
struct Node* node = createNode(data);
printf("Enter left child of %d:\n", data);
node->left = createTree();
printf("Enter right child of %d:\n", data);
node->right = createTree();
return node;
}
// Function to display the tree using inorder traversal
void inorderTraversal(struct Node* root) {
if (root == NULL)
return;
inorderTraversal(root->left);
printf("%d ", root->data);
inorderTraversal(root->right);
}
// Main function
int main() {
struct Node* root = NULL;
printf("Create Binary Tree:\n");
root = createTree();
printf("Inorder Traversal of the Binary Tree:\n");
inorderTraversal(root);
printf("\n");
return 0;
}
