【发布时间】:2014-03-30 22:51:03
【问题描述】:
我正在尝试编写一个程序,该程序将从文本文件中读取单词并将其插入二叉树。如果单词超过 10 个字符,则该单词将被剪切为 10 个字符。我觉得我真的很接近这个了,但是当我运行程序时,它崩溃了,我没有收到任何错误。我只用整数测试了二叉搜索树,它可以工作。我还测试了从文本文件中读取单词而不将其放入二叉树中,这也有效。但是当我将两者融合在一起时......这就是我遇到问题的地方。此外,文本文件的结尾用“#”表示。就这样休息;有道理。
#include <iostream>
#include <fstream>
#include <string>
using namespace std;
struct Node{
string data;
Node* left;
Node* right;
};
Node* GetNewNode(string data){
Node* newNode = new Node();
newNode->data=data;
newNode->left = newNode->right = NULL;
}
Node* Insert(Node* rootPtr,string data){
if(rootPtr == NULL){
rootPtr = GetNewNode(data);
return rootPtr;
}
else if(data<= rootPtr->data){
rootPtr->left = Insert(rootPtr->left,data);
}
else {
rootPtr->right = Insert(rootPtr->right,data);
}
return rootPtr;
}
int main() {
string word;
ifstream inFile;
Node* rootPtr = NULL; // Pointer to the root node
inFile.open("example.txt");
if (!inFile) {
cout << "Unable to open text file";
}
while (inFile >> word) {
rootPtr = Insert(rootPtr,word.substr(0,10));
if (word == "#")
break;
}
inFile.close();
}
感谢您的任何意见!
【问题讨论】:
-
我刚刚弄清楚程序挂断了什么。不确定在对数据进行排序时该怎么做。它不知道一个词是否大于另一个词。如果我们有狗、猫、鱼三个词,我试图按字母顺序排列。 Dog 是根节点,cat 是左孩子,fish 是右孩子。
标签: c++ indexing binary-tree