C problem I already have a completed Binary Search Tree clas
C++ problem.
I already have a completed Binary Search Tree class with all the functions working properly.
Now my task is to read a txt file contains integers into a Binary Search Tree. Sample txt file:
5 12 7 9 10 18 23 76 52
76
66
7 10 9 55 43 27 34 90
1
2
98 67 23 10 2 3 7 8 22 33
22
4
line one: data to fill a Binary Search Tree
line two: one value to search for and remove
line three: one additional value to add
and then keep repeating, meaning that my txt file contains 3 times of those 3 lines.
I want to know how to read these integers into my BST as required because I need to read the 1st line then stop before getting
to the next line but my method keep reading the whole txt file at once and idk how to fix. Here\'s my main at the moment:
BinarySearchTree<int> BST;
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()) {
fin.get(c);
if (c != \'\ \') {
fin >> value;
BST.insert(value);
}
}
Solution
#include <iostream>
#include \"NodeClass.h\"
#include <fstream>
using namespace std;
int main()
{
string myString;
BinaryTree myTree(\"\");
ifstream infile;
infile.open(\"Lincoln.txt\");
while(infile)
{
infile >> myString;
myTree.insert(myString, myTree.root);
}
ofstream outFile;
outFile.open(\"index.txt\");
myTree.print(myTree.root, outFile);
outFile.close();
}
NodeClass.cpp
#include <iostream>
#include \"NodeClass.h\"
using namespace std;
void BinaryTree::insert(ElementType data, TreeNode *&tree)
{
if (tree == NULL)
{
tree = new TreeNode(data);
}
else if(data < tree->data)
insert(data, tree->left);
else if(data > tree->data)
insert(data, tree->right);
else if(data == tree->data)
tree->count++;
}
void BinaryTree::display(TreeNode *tree, ostream& out)
{
if (tree != NULL)
{
display(tree->left, out);
out << tree->data<<\" \";
display(tree->right, out);
}
}
void BinaryTree::print(TreeNode *tree, ofstream& outFile)
{
if (tree != NULL)
{
outFile << tree->left;
outFile << tree->data << \" \" << tree->count;
outFile << tree->right;
}
}
NodeClass.h
#include <iostream>
#include <string>
#include <fstream>
#include <fstream>
using namespace std;
#ifndef TREENODE_H
#define TREENODE_H
typedef std::string ElementType;
class BinaryTree
{
public:
class TreeNode
{
public:
ElementType data;
int count;
TreeNode *left;
TreeNode *right;
TreeNode(ElementType new_data)
{ data = new_data; left = NULL; right = NULL;};
};
TreeNode *root;
BinaryTree(ElementType root_data)
{ root = new TreeNode(root_data); };
~BinaryTree() { delete root;};
void insert(ElementType data, TreeNode *&tree);
void display(TreeNode *tree, ostream& out);
void print(TreeNode *tree, ofstream& outFile);
};



