/*
Name: Nguyen Ngoc Hoang
Student COde: 08020167
K53D- UET- VNU
Assigment 01
DSA
*/
#include<iostream>
#include<string>
#include<fstream>
#include<algorithm>
#include<iomanip>
using namespace std;
struct Data // Data include keyword and number of occurrences
{
string key;
int count;
};
struct Node //A Node inclues Data, left and right
{
Data data;
Node* left;
Node* right;
Node(Data d,Node* l,Node* r)
{
data=d;
left=l;
right=r;
}
};
class BSTree
{
private:
static const int N = 100;
Node *root;
public:
//Construct an empty BSTree
BSTree()
{
root=NULL;
}
//Create a BSTree from a file
BSTree(BSTree &T , char *input)
{
ifstream fin;
fin.open(input);
if(!fin.good())
{
cout<<"Error!File wordcount.in is not exits!"<<endl;
cout<<"Please check again !"<<endl;
}
Data getdata;
getdata.count=1;
string keyword;
while(fin.good())
{
fin>>keyword;
strcpy(keyword,getdata.key);
T.InsertData(getdata);
}
fin.close();
}
//Destruct the BSTree
// ~BSTree();
int IsEmpty();
//Print all values of nodes inoder traversal
void PrintTree(char* output);
void Print_Tree(Node*,char* output);
//Insert a value to BSTree
void InsertData(Data DataInsert);
void AddNode(Node *v,Data DataInsert);
};
int BSTree::IsEmpty()
{
return root==NULL;
}
void BSTree::PrintTree(char* output)
{
Print_Tree(root,output);
}
void BSTree::Print_Tree(Node* p,char* output)
{
ofstream fout;
fout.open(output);
if(p!=NULL)
{
Print_Tree(p->left,output);
fout<<p->data.key<<"\t";
fout<<p->data.count<<endl;
//fout<<"hoang huong";
Print_Tree(p->right,output);
}
fout.close();
}
void BSTree::InsertData(Data DataInsert)
{
if(root==NULL) root=new Node(DataInsert,NULL,NULL );
else AddNode(root,DataInsert);
}
void BSTree::AddNode(Node *v,Data ValueInsert)
{
if(v->data.key==ValueInsert.key)
{
ValueInsert.count++;
return;
}
else
{
if(v->data.key > ValueInsert.key)
{
if(v->left!=NULL) AddNode(v->left,ValueInsert);
else v->left=new Node(ValueInsert,NULL,NULL);
}
else
{
if(v->right!=NULL) AddNode(v->right,ValueInsert);
else v->right=new Node(ValueInsert,NULL,NULL);
}
}
}
//main function
int main()
{
BSTree T;
BSTree Tree = BSTree(T ,"wordcount.in");
T.PrintTree("wordcount.out");
}
//count the number of Node
int CountNode(Node* root)
{
if(root=NULL) return 0;
else
{
int count=1;
return CountNode(root->left)+CountNode(root->right);
}
}
//Compare key of Node with a string
bool Compare(Node* n, string s)
{
while(true)
{
if (n==NULL) return false;
else if(s==(n->data).key) return true;
else if(s<n->data.key) n=n->left;
else n=n->right;
}
}