0% found this document useful (0 votes)
24 views2 pages

Binary Tree Implementation

Implementation of Binary tree
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
24 views2 pages

Binary Tree Implementation

Implementation of Binary tree
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd

Binary Tree Implementation

A Binary tree is implemented with the help of pointers. The first node in the tree is
represented by the root pointer. Each node in the tree consists of three parts, i.e., data, left
pointer and right pointer. To create a binary tree, we first need to create the node. We will
create the node of user-defined as shown below:

struct node
{
int data,
struct node *left, *right;
}
In the above structure, data is the value, left pointer contains the address of the left node,
and right pointer contains the address of the right node.

Binary Tree program in C

#include<stdio.h>
#include<malloc.h>
struct node
{
int data;
struct node *left, *right;
};
struct node *create();
void print(struct node *);
void main()
{
struct node *root;
root = create();
print(root);
}
struct node *create()
{
struct node *temp;
int data,choice;
temp = (struct node *)malloc(sizeof(struct node));
printf("Press 0 to exit\n");
printf("Press 1 for new node\n");
printf("Enter your choice : ");
scanf("%d", &choice);
if(choice==0)
{
return 0;
}
else
{
printf("Enter the data:");
scanf("%d", &data);
temp->data = data;
printf("Enter the left child of %d", data);
temp->left = create();
printf("Enter the right child of %d", data);
temp->right = create();
return temp;
}
}
void print(struct node *root)
{
if(root!=NULL)
{
print(root->left);
printf("%d", root->data);
print(root->right);
}
}

Output:
Press 0 to exit
Press 1 for new node
Enter your choice : 1
Enter the data: 10
Enter the left child of 10
Press 0 to exit
Press 1 for new node
Enter your choice : 1
Enter the data: 20
Enter the left child of 20
Press 0 to exit
Press 1 for new node
Enter your choice : 0
Enter the right child of 20
Press 0 to exit
Press 1 for new node
Enter your choice : 0
Enter the right child of 10
Press 0 to exit
Press 1 for new node
Enter your choice : 1
Enter the data: 30
Enter the left child of 30
Press 0 to exit
Press 1 for new node
Enter your choice : 0
Enter the right child of 30
Press 0 to exit
Press 1 for new node
Enter your choice : 0

201030

You might also like