Let us create a binary tree using recursion.
Sequence of calls is shown by nos in the below figure.
Let me show you a recursive create function here:
node* create()
{
node* curr;char x;
fflush(stdin);
scanf("%c",&x);
if(x==' ')
return NULL;
else
{
curr=(node*)malloc(sizeof(node));
curr->data=x;
printf("Enter left child of %c ",curr->data);
curr->left=create();
printf("Enter right child of %c ",curr->data);
curr->right=create();
return curr;
}
}
Note: Return statements are numbered to make your understanding clear.
Steps:
1.Create node A.
2.Create node B.
3.Create node C.
4.Make left pointer of C as NULL.
5.Make right pointer of C as NULL.
7.Create node D.
8.Make left pointer of D as NULL.
9.Make right pointer of D as NULL.
12.Create node E.
13.Make left pointer of E as NULL.
14.Make right pointer of E as NULL.
The binary tree is now created.
No comments:
Post a Comment