Hello,
I have been working on this code. What it does basically is read a text file, store the words in a binary search tree, prints out the words in alphabetical order along with line number where the word occur.
Example:
Input:
I need help with
this code
Output:
code 2
help 1
I 1 1
need 1 2
this 2 1
with 1 4
My code reads a text file, store it in a BST, prints out the word in alphabetical order. What I couldn't figure out is how to find the word's location in a line. If anyone has any ideas it will be highly appreciated.
#include <iostream>
#include <string>
#include <fstream>
using namespace std;
class BSTree
{
private:
struct treeNode
{
treeNode* left;
treeNode* right;
string word;
treeNode(string s)
{
word = s;
left = NULL;
right = NULL;
}
};
public:
treeNode* root;
BSTree()
{
root = NULL;
}
void insert(treeNode *&root, string newNode)
{
if(root == NULL)
{
root = new treeNode(newNode);
return;
}
else if(newNode < root->word)
{
insert(root->left, newNode);
}
else
{
insert(root->right, newNode);
}
}
void print(treeNode *node)
{
if(node != NULL)
{
print(node->left);
cout << node->word << endl;
print(node->right);
}
}
};
main()
{
ifstream fis;
string str = "";
string fileName
BSTree bst;
cout << "Enter file: " << endl;
cin >> fileName;
fis.open(fileName.c_str());
while(!fis.eof())
{
fis >> str;
bst.insert(bst.root,str);
}
bst.print(bst.root);
}