define tree data structure and display how to make a tree.
Description:
A tree data structure that are based on hierarchical tree structure with sets of nodes. A tree is a acyclic connected graph with zero or more children nodes and at most one parent nodes.Code:
#include <stdio.h>
#include <stdlib.h>
struct node
{
int data;
struct node *lchild, *rchild;
};
struct node *insertN(struct node *p,int val)
{
struct node *temp1,*temp2;
if(p == NULL)
{
p = (struct node *) malloc(sizeof(struct node));
if(p == NULL)
{
printf("Cannot allocate memory\n");
exit(0);
}
p->data = val;
p->lchild=p->rchild=NULL;
}
else
{
temp1 = p;
while(temp1 != NULL)
{
temp2 = temp1;
if( temp1 ->data > val)
temp1 = temp1->lchild;
else
temp1 = temp1->rchild;
}
if( temp2->data > val)
{
temp2->lchild = (struct node*)malloc(sizeof(struct node));
temp2 = temp2->lchild;
if(temp2 == NULL)
{
printf("Cannot allocate memory\n");
exit(0);
}
temp2->data = val;
temp2->lchild=temp2->rchild = NULL;
}
else
{
temp2->rchild = (struct node*)malloc(sizeof(struct node));
temp2 = temp2->rchild;
if(temp2 == NULL)
{
printf("Cannot allocate memory\n");
exit(0);
}
temp2->data = val;
temp2->lchild=temp2->rchild = NULL;
}
}
return(p);
}
void display(struct node *p)
{
if(p != NULL)
{
display(p->lchild);
printf("%d\t",p->data);
display(p->rchild);
}
}
void main()
{
struct node *root = NULL;
int n,x;
printf("Enter the number of nodes for tree\n");
scanf("%d",&n);
while( n -- > 0)
{
printf("Enter the data value\n");
scanf("%d",&x);
root = insertN(root,x);
}
display(root);
}
0 comments:
Speak up your mind
Tell us what you're thinking... !