文字列を収集してポスト順に並べるバイナリ検索ツリーを使用しています。文字列が表示される行番号を示すリストも使用します。BST を適切に動作させることはできますが、最終的には出力が正しくありません。重複している単語に出くわしたときに問題が発生していると思います。重複した単語に行番号を追加すると、出力が台無しになります。
私の出力は次のようになります
hawaii 3
hello 1
is 3
paradise 2
to 2
welcome 2
wonderful 1 3
world 1
ただし、これを出力として取得します
Contents of tree:
hello 1
Contents of tree:
hello 1
wonderful 1
.
.
.
Contents of tree:
hawaii 3
hello 1
is 3
paradise 2
to 2
welcome 2
wonderful 1
world 1
Contents of tree:
is 3
paradise 2
to 2
welcome 2
wonderful 1 3
world 1
Press any key to continue . . .
これが主なロジックです
struct TreeNode
{
string data;
list<int> lineNum;
TreeNode *left;
TreeNode *right;
TreeNode(string str,list<int> num)
{
data = str;
lineNum = num;
left = NULL;
right = NULL;
}
};
void insert(TreeNode *&root, string newNode,list<int> num)
{
if(root == NULL)
{
root = new TreeNode(newNode,num);
}
else if(newNode < root -> data)
{
insert(root -> left, newNode,num);
}
else
{
insert(root -> right, newNode,num);
}
}
bool treeContains( TreeNode *root, string item )
{
if ( root == NULL )
{
return false;
}
else if ( item == root->data)
{
return true;
}
else if ( item < root->data )
{
return treeContains( root->left, item );
}
else
{
return treeContains( root->right, item );
}
}
void treeInsert(TreeNode *&root, string newItem,int num)
{
list<int> temp;
temp.push_back(num);
if ( root == NULL )
{
root = new TreeNode(newItem,temp );
return;
}
else if ( newItem < root->data )
{
treeInsert( root->left, newItem,num );
}
else
{
treeInsert( root->right, newItem,num );
}
}
void printTree(TreeNode *node)
{
list<int>::iterator i;
if ( node != NULL )
{
printTree(node->left);
cout <<node->data;
for( i = node->lineNum.begin(); i != node ->lineNum.end(); ++i)
cout<<" "<<*i;
cout << endl;
printTree(node->right);
}
}
TreeNode search(TreeNode *root, string item)
{
while ( root != NULL )
{
if(item == root->data)
{
break;
}
if ( item > root->data )
{
root = root-> right;
}
else if(item < root->data )
{
root = root-> left;
}
if(root == NULL)
{
cout << "error";
}
}
return *root;
}
int main()
{
TreeNode *root;
root = NULL;
ifstream test("test.txt");
istringstream strLine;
string line, word;
list<int> lineNum;
int currentLine=0;
// Go line by line
while (getline(test,line))
{
++currentLine;
strLine.clear();
strLine.str(line);
lineNum.push_back(currentLine);
// Now from the line read word by word
while (strLine >> word)
{
// if word is already in tree search tree for node and line number
if (treeContains(root,word))
{
*root = search(root,word);
root->lineNum.push_back(currentLine);
cout << "\nContents of tree:\n\n";
printTree(root);
}
// if word is new add to tree insert node
else
{
treeInsert(root,word,currentLine);
cout << "\nContents of tree:\n\n";
printTree(root);
}
}
}
}
入力テキストは次のようになります。
hello wonderful world
welcome to paradise
hawaii is wonderful
よろしくお願いします!