How to Create a Binary Tree in C: Syntax and Example
To create a binary tree in C, define a
struct with data and two pointers for left and right children. Then, dynamically allocate nodes using malloc and link them to form the tree structure.Syntax
A binary tree node in C is defined using a struct that contains a data field and two pointers to its left and right child nodes.
Each part means:
int data;stores the value of the node.struct Node *left;points to the left child node.struct Node *right;points to the right child node.
c
struct Node {
int data;
struct Node *left;
struct Node *right;
};Example
This example shows how to create a simple binary tree with three nodes and print their values in preorder (root, left, right).
c
#include <stdio.h>
#include <stdlib.h>
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));
if (newNode == NULL) {
printf("Memory allocation failed\n");
exit(1);
}
newNode->data = data;
newNode->left = NULL;
newNode->right = NULL;
return newNode;
}
// Preorder traversal to print nodes
void preorder(struct Node* root) {
if (root == NULL) return;
printf("%d ", root->data);
preorder(root->left);
preorder(root->right);
}
int main() {
// Create root node
struct Node* root = createNode(1);
// Create left and right children
root->left = createNode(2);
root->right = createNode(3);
printf("Preorder traversal: ");
preorder(root);
printf("\n");
// Free allocated memory
free(root->left);
free(root->right);
free(root);
return 0;
}Output
Preorder traversal: 1 2 3
Common Pitfalls
Common mistakes when creating binary trees in C include:
- Not initializing child pointers to
NULL, which can cause undefined behavior. - Forgetting to allocate memory with
mallocbefore using nodes. - Not freeing allocated memory, causing memory leaks.
- Mixing up left and right child pointers.
Always check if malloc returns NULL in real programs to handle memory allocation failure.
c
/* Wrong way: Not initializing children */ struct Node* wrongNode = (struct Node*)malloc(sizeof(struct Node)); wrongNode->data = 5; // left and right pointers are uninitialized here /* Right way: Initialize children to NULL */ struct Node* rightNode = (struct Node*)malloc(sizeof(struct Node)); rightNode->data = 5; rightNode->left = NULL; rightNode->right = NULL;
Quick Reference
- Define a
structwith data and two child pointers. - Use
mallocto create nodes dynamically. - Initialize child pointers to
NULL. - Link nodes by assigning child pointers.
- Free memory with
freewhen done.
Key Takeaways
Define a struct with data and left/right pointers to create binary tree nodes.
Use malloc to allocate memory and initialize child pointers to NULL.
Link nodes by assigning left and right pointers to build the tree.
Always free allocated memory to avoid memory leaks.
Check malloc return values in real applications for safe memory use.