In text processing, it is common to study the number of distinct words used in the text together with their word counts. You can assume that all the words are in lowercase and no punctuation marks are in the text; and we would like to use BST to store and to sort all the distinct words.
Open this infile.txt to read text and store in binary tree
Code:
you can fool some of the people
some of the times and all of the people some of
the times and not all of the people all of them times
fool some of you and not all of you
Here is my code, a BST (Binary search tree) code that read infile.txt and output the number of distinct words in the infile.txt.
Code:
// A BST with duplicated nodes
#include <iostream>
#include <fstream>
using namespace std;
const int MAX = 100;
const char fileName [MAX] = "infile.txt";
class BST
{
public:
BST ();
void insert (char);
void print () const;
private:
struct Node;
typedef Node* NodePtr;
struct Node
{
char word;
int count;
NodePtr left, right;
};
NodePtr root;
void insert (NodePtr&, char);
void inorderPrint (const NodePtr&) const;
};
int main ()
{
BST t;
fstream afile;
char item;
afile.open (fileName, ios::in); // open to read
if (!afile) {
cout << "Error, file cannot be opened" << endl;
}
while (afile >> item)
{
t.insert (item);
}
t.print ();
afile.close();
}
BST::BST ()
{
root = NULL;
}
void BST::insert (char item)
{
insert (root, item);
}
void BST::print () const
{
inorderPrint (root);
}
void BST::insert (NodePtr& root, char item)
{
if (root == NULL)
{
NodePtr temp = new Node;
temp -> word = item;
temp -> count = 1;
temp -> left = NULL;
temp -> right = NULL;
root = temp;
}
else if (root -> word == item)
(root -> count)++;
else if (root -> word > item)
insert (root -> left, item);
else
insert (root -> right, item);
}
void BST::inorderPrint (const NodePtr& root) const
{
if (root != NULL)
{
inorderPrint (root -> left);
cout << root -> word << "\t"
<< root -> count
<< " times"
<< endl;
inorderPrint (root -> right);
}
}
But it produced this result

Instead of this
Upon execution of your program, the following table is displayed on screen; as can be seen that the words (left column) are sorted in order:

I am really a newbie on this, I really hope someone can enlighten me on this.