In C# 6.1 Write a program to store and display a tree. You may limit the type of
ID: 3832635 • Letter: I
Question
In C#
6.1 Write a program to store and display a tree. You may limit the type of trees that it will process, e.g. complete binary trees, or heaps. You may choose the data structures to store and process the tree, e.g. an array. In your test program, be sure to print the node values in tree “format”.
6.2 Write a function to add an element to an existing tree.
6.3 Write a function to delete an element from an existing tree.
6.4 Write a function to perform an “in-order” traversal on an existing tree.
6.5 Write a function to perform an “pre-order” traversal on an existing tree.
6.6 Write a function to perform an “post-order” traversal on an existing tree.
6.7 Write a function to perform an “level-order” traversal on an existing tree.
6.8 Write a function to find the children of a specified node.
6.9 Write a function to find the parent of a specified node.
Explanation / Answer
#include<stdio.h>
#include<conio.h>
struct node
{
int data;
struct node* lchild;
struct node* rchild;
};
struct node* create(struct node*);
void inorder(struct node* );
void preorder(struct node* );
void postorder(struct node* );
void display(struct node *);
void main()
{
struct node* root=NULL;
root=(struct node*)create(root);
printf(“display”);
printf(“ inorder is”);
inorder(root);
printf(“ preorder is”);
preorder(root);
printf(“ postorder is”);
postorder(root);
printf(“ display of tree is ”);
display(root);
inorder(root);
getch();
}
struct node* create(struct node* root)
{
struct node* temp,*newn;
int i,size;
clrscr();
printf(“enter size”);
scanf(“%d”,&size);
for(i=0;i<size;i++)
{
newn=(struct node*)malloc(sizeof(struct node));
newn->lchild=newn->rchild=NULL;
printf(“enter data”);
scanf(“%d”,&newn->data);
if(root==NULL)
{
root=newn;
}
else
{
temp=root;
while(temp!=NULL)
{
if(temp->data>newn->data)
{
if(temp->lchild!=NULL)
{
temp=temp->lchild;
}
else
{
temp->lchild=newn;
break;
}
}
else
{
if(temp->rchild!=NULL)
{
temp=temp->rchild;
}
else
{
temp->rchild=newn;
break;
}
}
}
}
}
return root;
}
// 6.4 inorder
void inorder(struct node* root)
{
if(root!=NULL)
{
inorder(root->lchild);
printf(“%d “,root->data);
inorder(root->rchild);
}
}
// 6.5 preorder
void preorder(struct node* root)
{
if(root!=NULL)
{
printf(“%d “,root->data);
preorder(root->lchild);
preorder(root->rchild);
}
}
//6.6 post-order
void postorder(struct node* root)
{
if(root!=NULL)
{
postorder(root->lchild);
postorder(root->rchild);
printf(“%d “,root->data);
}
}
// 6.1 store and display
void display(struct node * root)
{
struct node * temp=root,*temp1;
if(temp)
{
if(temp->lchild)
display(temp->lchild);
if(temp->rchild)
display(temp->rchild);
temp1=temp->lchild;
temp->lchild=temp->rchild;
temp->rchild=temp1;
}
}