Thursday, February 12, 2015
C Program to Create a Binary Tree Using Recursion Linked Representation
![C Program to Create a Binary Tree Using Recursion [Linked Representation] C Program to Create a Binary Tree Using Recursion [Linked Representation]](https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEjGLSWZDnJJqjV1qzz7_8HUKMvd34NcekdXEWE_BnrB0EMwmONwXoXSjPaKUtk9c-TNQVA2JKbUuuHOR3SYWjH2WuDnW8onVX6Ksqu12JCsexSiUQFlAuINHo2sSs4vos0ueU0mhKloA8el/s640/C+Program+to+Create+a+Binary+Tree+Using+Recursion+%255BLinked+Representation%255D+1.jpg)
What is Binary Tree?
A tree is said to be a binary tree if each node of the tree can have maximum of two children. Children of a node of binary tree are ordered. One child is called “left” child and the other is called “right” child. An example of binary tree is shown in below diagram.
![C Program to Create a Binary Tree Using Recursion [Linked Representation] C Program to Create a Binary Tree Using Recursion [Linked Representation]](https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEg-DMCVlJV8IlvtlvjHSAwFhxej9vLkzzlEGb1yzy0OJOK2ergbYUjFoowFlRFTr-7vsm5qjFMAGhuxIeOR3e2IHJ1WXWFlB66yTgPgt0xXW16ayJ9OLt-I0raOO8bPiAG14hIF0XQWXdHN/s640/C+Program+to+Create+a+Binary+Tree+Using+Recursion+%5BLinked+Representation%5D+2.jpg)
Creation of Binary Tree Using Recursion
A binary tree can be created recursively. The program will work as follow:
1. Read a data in x.
2. Allocate memory for a new node and store the address in pointer p.
3. Store the data x in the node p.
4. Recursively create the left subtree of p and make it the left child of p.
5. Recursively create the right subtree of p and make it the right child of p.
Also Read: C++ program to create Facebook Login screen
Also Read: C++ Program For Linked List Representation Of Linear Queue
The program is written in C language which allows linked representation of binary tree. Code will be as follow:
#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:
",x);
",x);
p->left=create();
printf("Enter right child of %d:
",x);
",x);
p->right=create();
return p;
}
void preorder(node *t) //address of root node is passed in t
{
if(t!=NULL)
{
printf("
%d",t->data); //visit the root
%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("
The preorder traversal of tree is:
");
The preorder traversal of tree is:
");
preorder(root);
return 0;
}
In the above program I have used preorder traversal to just show that the tree is created properly or not. You can use any other traversal method here.
Subscribe to:
Post Comments (Atom)
No comments:
Post a Comment
Note: Only a member of this blog may post a comment.