Binary Tree using Linked List in C
Creating a binary tree using linked list in C involves defining a structure for tree nodes and then implementing functions to manipulate the tree. Here’s a basic example of how to create a binary tree using linked lists in C and data structure.
What is Binary Tree?
A binary tree is a hierarchical structure in computer science where each node can have up to two children. It’s commonly used for organizing data. Binary Search Trees (BSTs) are a type of binary tree optimized for efficient searching. Balancing techniques maintain efficiency.
Binary Tree using Linked List in C program
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 | //binary tree using linked list in c #include <stdio.h> #include <stdlib.h> //structure for a tree node struct TreeNode { int data; struct TreeNode* left; struct TreeNode* right; }; // create new tree node function struct TreeNode* createNode(int data) { struct TreeNode* newNode = (struct TreeNode*)malloc(sizeof(struct TreeNode)); if (newNode == NULL) { printf("Memory allocation failed!\n"); exit(1); } newNode->data = data; newNode->left = NULL; newNode->right = NULL; return newNode; } // print tree in tree like format void printTree(struct TreeNode* root, int level) { if (root == NULL) { return; } printTree(root->right, level + 1); for (int i = 0; i < level; i++) { printf(" "); } printf("%d\n", root->data); printTree(root->left, level + 1); } int main() { struct TreeNode* root = NULL; // Insert nodes in binary tree root = createNode(1); root->left = createNode(2); root->right = createNode(3); root->left->left = createNode(4); root->left->right = createNode(5); root->right->left = createNode(6); root->right->right = createNode(7); printf("Binary Tree \n"); printTree(root, 0); return 0; } |
Output