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

C++ problem How to write my Binary Search Tree into an output file. I have a com

ID: 3937819 • Letter: C

Question

C++ problem

How to write my Binary Search Tree into an output file. I have a completed BST.h file and main file reading a txt file into a BST and now I

want to write it into and output file. My professor said this:

A Word About Printing

Note that you will need to alter the signatures of preOrderPrint, inOrderPrint and postOrderPrint to take in information about a file.

Part of my BST.h file:

private:
   struct Node {
       bstitem data;
       Node* left;
       Node* right;

       Node(bstitem newdata) :
               data(newdata), left(NULL), right(NULL) {
       }
   };

   typedef struct Node* NodePtr;
   NodePtr root;

...

...

void inOrderPrintHelper(NodePtr root);

   void preOrderPrintHelper(NodePtr root);

   void postOrderPrintHelper(NodePtr root);

public:

......

void inOrderPrint();
   void preOrderPrint();
   void postOrderPrint();

My main file:

int main() {

   int value;
   char c;
   ifstream fin;
   fin.open("infile.txt");

   if (fin.fail()) {
       cout << "Input failed. ";
       exit(-1);
   }

   ofstream fout;
   fout.open("outfile.txt");
   if (fout.fail()) {
       cout << "Output file failed to open. ";
       exit(-1);
   }

   while (!fin.eof()) {
.......
       BST.preOrderPrint();
       BST.inOrderPrint();
.........

.........
       BST.postOrderPrint();
..........
}

"....." are some codes in between not important. I just want to know what I need to change to instead of printing onto the console now I'm writing

it onto a file.

Here is what I'm doing but it's still incorrect: Example of just 1 inOrderPrint

private:

void inOrderPrintHelper(NodePtr root, ofstream &S);

public:

void inOrderPrint(ofstream &S);

template<class bstitem>
void BinarySearchTree<bstitem>::inOrderPrintHelper(NodePtr root, ofstream &S) {
   if (root != NULL) {
       inOrderPrintHelper(root->left, &S); <--- error here
       S << root->data << " ";
       inOrderPrintHelper(root->right, &S); <--- error here
   }
}

template<class bstitem>
void BinarySearchTree<bstitem>::inOrderPrint(ofstream &S) {
   inOrderPrintHelper(root, &S); <--- error here
   S << endl;
}

Explanation / Answer

Use this method to BSt to output file.

void writeBinaryTree(BinaryTree *bhbh, ostream &out) {
if (!bhbh) {
out << "# ";
} else {
out << bhbh->data << " ";
writeBinaryTree(bhbh->left, out);
writeBinaryTree(bhbh->right, out);
}
}

Hire Me For All Your Tutoring Needs
Integrity-first tutoring: clear explanations, guidance, and feedback.
Drop an Email at
drjack9650@gmail.com
Chat Now And Get Quote