A. (10 points) Write a program to store a tree as an array. In your test program
ID: 3889117 • Letter: A
Question
A. (10 points) Write a program to store a tree as an array. In your test program, be sure to print the array values, and to print the values in tree “format”.
B. (5 points) Write a function to add an element to an existing tree.
C. (5 points) Write a function to delete an element from an existing tree.
D. (5 points) Write a function to perform an “in-order” traversal on an existing tree.
E. (5 points) Write a function to perform an “pre-order” traversal on an existing tree.
F. (5 points) Write a function to perform an “post-order” traversal on an existing tree.
G. (5 points) Write a function to perform an “level-order” traversal on an existing tree.
H. (5 points) Write a function to find the children of a specified node.
I. (5 points) Write a function to find the parent of a specified node.
Explanation / Answer
This program print tree format horizontally:
#include<conio.h>
#include<stdio.h>
#define COUNT 10
int arr[100],count;
int x=0;
void inorder(int pos, int space)
{
int i,j,k=0;
space+=COUNT;
i = 2*pos + 1;
if(arr[i] != 0)
inorder(i,space);
printf(" ");
for ( k = COUNT; k < space; k++)
printf(" ");
printf("%d",arr[pos]);
j = 2*pos +2;
if(arr[j] != 0)
inorder(j,space);
}
void main()
{
int i,num,choice;
count = 0;
clrscr();
for(i=0;i<100;i++)
arr[i] = 0;
do
{
printf(" enter your choice 1.Insert into tree 2.delete from tree 3. search for an element in tree 4. inorder traversal ");
printf("5. exit ");
scanf("%d",&choice);
switch(choice)
{
case 1:
printf("enter element"); //to add an element to an existing tree
scanf("%d",&num);
arr[count] = num;
count++;
break;
case 2: //to delete an element from an existing tree.
printf(" enter the element to be deleted");
scanf("%d",&num);
for(i=0;i<count;i++)
{
if(arr[i]==num) {
count--;
arr[i] = arr[count];
arr[count] = 0;
break;
}}
if(i==count)
printf(" element not found:");
break;
case 3: // to find the children of a specified node
printf(" enter the element to be searched:");
scanf("%d",&num);
for(i=0;i<count;i++)
{
if(arr[i]==num) {
printf(" element found ");
break;
} }
if(i==count)
printf(" element not found ");
break;
case 4: //to perform an “in-order” traversal on an existing tree
inorder(0,0);
break;
}
}while(choice != 5);
getch();
}
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.