Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

help with q1,q2,q3 with seperate code for each of them in c++ Lab on Trees In cl

ID: 3586193 • Letter: H

Question

help with q1,q2,q3 with seperate code for each of them in c++

Lab on Trees In class you learned that the binary tree data-structure could represented in computer memory contiguously or by random access. Using principled object oriented programming, represent a tree using contiguous access. The tree will be inputted into the computer layer-by-layer starting at the root. Input is terminated with-1 For example blue green yellow pink red purple orange black brown -1 Which yield the following tree structure blue green yello pink purple orange black Question 1. Output a pre-order traversal of the input tree. Output should all be on one line. e.g. output: blue green pink black brown red yellow purple orange put a In-order tra should all ttree. Output s e.g. output black pink brown green red blue purple yellow orange Question 3. Output a post-order traversal of the input tree. Output should all be on one line e.g. output: black brown pink red green purple orange yellow blue

Explanation / Answer

Sol-1: pre-order traversal

#include<iostream>
#include<cstring>

using namespace std;

void preorder(char [][20], int, int);

int main(){
   //we can add 30 nodes..
   char tree[30][20],temp[20];
   cin >> temp;
   int i=0,count=0;
   while(strcmp(temp,"-1")){
       strcpy(tree[count++],temp);
       cin >> temp;
   }
   preorder(tree,0,count);
      
   return 0;
}
void preorder(char tree[][20],int pos,int size){
   if(pos<size){
       cout << tree[pos] << " ";
       preorder(tree,2*pos+1,size);
       preorder(tree,2*pos+2,size);
   }
}

Sol-2: In-Order traversal

#include<iostream>
#include<cstring>

using namespace std;

void inorder(char [][20], int, int);

int main(){
  
   char tree[30][20],temp[20];
   cin >> temp;
   int i=0,count=0;
   while(strcmp(temp,"-1")){
       strcpy(tree[count++],temp);
       cin >> temp;
   }
   inorder(tree,0,count);
      
   return 0;
}
void inorder(char tree[][20],int pos,int size){
   if(pos<size){
       inorder(tree,2*pos+1,size);
       cout << tree[pos] << " ";
       inorder(tree,2*pos+2,size);
   }
}

Sol-3: Post-Order traversal

#include<iostream>
#include<cstring>

using namespace std;

void postorder(char [][20], int, int);

int main(){
  
   char tree[30][20],temp[20];
   cin >> temp;
   int i=0,count=0;
   while(strcmp(temp,"-1")){
       strcpy(tree[count++],temp);
       cin >> temp;
   }
   postorder(tree,0,count);
      
   return 0;
}
void postorder(char tree[][20],int pos,int size){
   if(pos<size){
       postorder(tree,2*pos+1,size);
       postorder(tree,2*pos+2,size);
       cout << tree[pos] << " ";
   }
}