Binary tree in C


In this tutorial we will create a basic binary tree with the help of linked list. Our tree will be having one root node and two children.

Create a structure

struct node{
    int data;
    struct node* left;
    struct node* right;
    };  

Code to Insert element into node

  • Create a new node.
  • Add data to the new node.
  • Check the root node for empty position.
  • Add the new node to the left or right link of the root element.
void insert(struct node** t, int data){
    struct node* temp;
    temp = (struct node*)malloc(sizeof(struct node));
    temp->data = data;
    if((*t)->left==NULL){
       (*t)->left = temp;
    }else{
       (*t)->right = temp;
    }
}

Complete code of basic binary tree

  • Include malloc header file.
    #include <malloc.h>
  • Create a structure which will be holding information about our node.
  • Create a new root node.
  • Allocate memory to root node.
     tree = (struct node*)malloc(sizeof(struct node));
  • Insert the left and right child.
    insert(&tree, 6);
    insert(&tree, 3);

Binary tree

#include <stdio.h>
#include <string.h>
#include <malloc.h>
struct node{
    int data;
    struct node* left;
    struct node* right;
    };    
void insert(struct node**, int);    
main()
{
   struct node* tree;
 
   tree = (struct node*)malloc(sizeof(struct node));
   tree->data = 5;
   insert(&tree, 6);
   insert(&tree, 3);
   printf("\nroot:%d\n", tree->data);
   printf("\nleft child:%d\n", tree->left->data);
   printf("\nright child:%d\n", tree->right->data);
   
}

void insert(struct node** t, int data){
    struct node* temp;
    temp = (struct node*)malloc(sizeof(struct node));
    temp->data = data;
    if((*t)->left==NULL){
       (*t)->left = temp;
    }else{
       (*t)->right = temp;
    }
}

Output :

Note : In Binary tree, each node have atmost two children.

In the next tutorial we will study about creation of binary tree which is having multiple nodes. We will also study about BST which stands for binary search trees.