C Program to Implement Create and Display Operation for a Binary Tree
A Binary Tree is a hierarchical data structure where each node can have at most two children: a left child and a right child. In this program, we will implement create and display operations for a binary tree in a simple, student-friendly way.
📝 Problem Statement
Q1. A) Write C programs to implement create and display operation for binary tree.
💡 Logic (Student-Friendly Steps)
🔹 Create Operation
- Define a structure for a node containing:
dataleftpointerrightpointer
- Create a function to dynamically allocate a new node.
- Manually link nodes or accept input from the user to build the tree.
🔹 Display Operation
- Use a recursive function to traverse the tree.
- We can use Preorder Traversal (Root → Left → Right) to display nodes.
💻 Source Code (Simple Version)
#include <stdio.h>
#include <stdlib.h>
// Node structure
struct node
{
int data;
struct node *left;
struct node *right;
};
// Function to create a new node
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;
}
// Function to display tree (Preorder Traversal)
void displayTree(struct node* root)
{
if(root == NULL)
return;
printf("%d ", root->data); // Visit root
displayTree(root->left); // Traverse left subtree
displayTree(root->right); // Traverse right subtree
}
int main()
{
struct node* root = NULL;
int n, value, i;
printf("Enter number of nodes: ");
scanf("%d", &n);
if(n <= 0)
{
printf("Tree cannot be created.\n");
return 0;
}
// Create root node
printf("Enter value for root node: ");
scanf("%d", &value);
root = createNode(value);
// Insert remaining nodes manually (for simplicity)
struct node* temp;
for(i = 1; i < n; i++)
{
printf("Enter value for node %d: ", i+1);
scanf("%d", &value);
struct node* newnode = createNode(value);
temp = root;
while(1)
{
if(temp->left == NULL)
{
temp->left = newnode;
break;
}
else if(temp->right == NULL)
{
temp->right = newnode;
break;
}
else
{
temp = temp->left; // Move to left for next insertion
}
}
}
printf("Binary Tree nodes (Preorder Traversal):\n");
displayTree(root);
return 0;
}
🖥️ Sample Output
Enter number of nodes: 5
Enter value for root node: 10
Enter value for node 2: 20
Enter value for node 3: 30
Enter value for node 4: 40
Enter value for node 5: 50
Binary Tree nodes (Preorder Traversal):
10 20 40 50 30
🎓 Viva Questions with Answers
1. What is a binary tree?
A tree in which each node has at most two children: left and right.
2. What is the root node?
The first node of the tree, which acts as the starting point.
3. What is a leaf node?
A node with no left or right children.
4. What is preorder traversal?
Visiting Root → Left → Right recursively.
5. How do you insert a new node in a binary tree?
By creating a node and linking it to the first available left or right child in a simple implementation.
