【问题标题】:c++ input words from text file in binary search treec ++从二进制搜索树中的文本文件输入单词
【发布时间】: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


【解决方案1】:

你需要从GetNewNode返回newNode

此外,您应该在插入单词之前检查 #,除非您希望在树中使用“#”。

【讨论】:

  • 所以我不清楚的一件事是,它是如何排列单词的?你认为它是按字母顺序执行的,还是取决于单词的大小(字节)。
  • 它使用std::string
猜你喜欢
  • 2016-02-28
  • 1970-01-01
  • 2020-02-16
  • 2014-11-02
  • 2013-05-27
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多