Binary Tree in C Using Recursion

Here you will get the program to make a binary tree in C utilizing recursion.

What is Binary Tree?

A tree is said to be a binary tree if every hub of the tree can have a limit of two youngsters.

Offspring of a hub of a binary tree is requested. One youngster is called left kid and the other is called the right kid.

A case of a binary tree is appeared in underneath chart.

Making of Binary Tree Using Recursion

A binary tree can be made recursively. The program will function as pursue:

Peruse information in x.

Apportion memory for another hub and store the location in pointer p.

Store the information x in the hub p.

Recursively make the left subtree of p and make it the left offspring of p.

Recursively make the privilege subtree of p and make it the correct offspring of p.

The program is written in C language which permits connected portrayal of a binary tree. Code will be:

Program

#include<stdio.h>
 
typedef struct node
{
	int data;
	struct node *left;
	struct node *right;
} node;
 
node *create()
{
	node *p;
	int x;
	printf("Enter data(-1 for no data):");
	scanf("%d",&x);
	
	if(x==-1)
		return NULL;
	
	p=(node*)malloc(sizeof(node));
	p->data=x;
	
	printf("Enter left child of %d:\n",x);
	p->left=create();
 
	printf("Enter right child of %d:\n",x);
	p->right=create();
	
	return p;
}
 
void preorder(node *t)		//address of root node is passed in t
{
	if(t!=NULL)
	{
		printf("\n%d",t->data);		//visit the root
		preorder(t->left);		//preorder traversal on left subtree
		preorder(t->right);		//preorder traversal om right subtree
	}
}
 
int main()
{	
	node *root;
	root=create();
	printf("\nThe preorder traversal of tree is:\n");
	preorder(root);
	
	return 0;
}

Output

Enter data(-1 for no data):5
Enter left child of 5:
Enter data(-1 for no data):7
Enter left child of 7:
Enter data(-1 for no data):8
Enter left child of 8:
Enter data(-1 for no data):3
Enter left child of 3:
Enter data(-1 for no data):-1
Enter right child of 3:
Enter data(-1 for no data):-1
Enter right child of 8:
Enter data(-1 for no data):-1
Enter right child of 7:
Enter data(-1 for no data):-1
Enter right child of 5:
Enter data(-1 for no data):-1

The preorder traversal of tree is:

5
7
8
3

In the above program, I have utilized preorder traversal to simply show that the tree is made appropriately or not.

You can utilize some other traversal technique here. Remark beneath in the event that you discovered anything inaccurate

or missing in the above program for the binary tree in C.

Leave a Comment

error: Alert: Content is protected!!