Example : A simple program in C to create a Binary Tree up to 3 levels.
#include <stdio.h>
#include <stdlib.h>
// Define structure of a tree node
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;
}
int main()
{
int val;
// Create root node
printf("Enter value for root: ");
scanf("%d", &val);
struct Node* root = createNode(val);
// Level 2 (children of root)
printf("Enter value for left child of %d: ", root->data);
scanf("%d", &val);
root->left = createNode(val);
printf("Enter value for right child of %d: ", root->data);
scanf("%d", &val);
root->right = createNode(val);
// Level 3 (children of left child)
printf("Enter value for left child of %d: ", root->left->data);
scanf("%d", &val);
root->left->left = createNode(val);
printf("Enter value for right child of %d: ", root->left->data);
scanf("%d", &val);
root->left->right = createNode(val);
// Level 3 (children of right child)
printf("Enter value for left child of %d: ", root->right->data);
scanf("%d", &val);
root->right->left = createNode(val);
printf("Enter value for right child of %d: ", root->right->data);
scanf("%d", &val);
root->right->right = createNode(val);
// Display the tree in simple form
printf("\nBinary Tree (3 Levels):\n");
printf(" %d\n", root->data);
printf(" / \\\n");
printf(" %d %d\n", root->left->data, root->right->data);
printf(" / \\ / \\\n");
printf(" %d %d %d %d\n",
root->left->left->data,
root->left->right->data,
root->right->left->data,
root->right->right->data);
return 0;
}
Output:
Enter value for root: 400
Enter value for left child of 400: 10
Enter value for right child of 400: 20
Enter value for left child of 10: 30
Enter value for right child of 10: 40
Enter value for left child of 20: 50
Enter value for right child of 20: 20
Binary Tree (3 Levels):
400
/ \
10 20
/ \ / \
30 40 50 20
0 Comments