Batch - B Practical Test Question

Batch - B Practical Test Question
Batch - B Practical Test Question

TREE Create and Print Program in C

#include<stdio.h>
#include<stdlib.h>

struct Node
{
int data;
struct Node *rChild;
struct Node *lChild;
};

struct Node *ROOT=NULL,*head=NULL,*temp=NULL;

void createTree(int);
struct Node *createNode(int);
void printTree();

int main()
{
int no;
printf("How Many Nodes You want to Enter in TREE : ");
scanf("%d",&no);
createTree(no);
printf("\nCreate DONE");
head=ROOT;
printTree(head);
return 0;
}

struct Node *createNode(int n)
{
temp=(struct Node *)malloc(sizeof(struct Node)*1);
temp->data=n;
temp->lChild=NULL;
temp->rChild=NULL;
return temp;
}
void createTree(int no)
{
int val;
while(no>0)
{
printf("\n Enter Data for Node : ");
scanf("%d",&val);
temp=createNode(val);
if(ROOT==NULL)
{
ROOT=temp;
}
else
{
head=ROOT;
while(((head->lChild!=NULL))&&(head->data > temp->data) || ((head->rChild!=NULL)&&(head->data < temp->data)))
{
if(temp->data > head->data)
{
head=head->rChild;
}
else
{
head=head->lChild;
}
}

if(temp->data > head->data)
{
head->rChild=temp;
}
else
{
head->lChild=temp;
}
}
no--;
}
}

void printTree(struct Node *head)
{
if(head==NULL)
{
return;
}
printTree(head->lChild);
printf("%d ",head->data);
printTree(head->rChild);
}

Comments