1

I am trying to write a program that will read words from a text file and insert it into a binary tree. If the word is more than 10 characters, then the word will get cut at 10 characters. I feel like I am really close to getting this but when I run the program, it crashes and I receive no errors. I tested the binary search tree with just integers and it works. I also tested reading the words from a text file without putting it in a binary tree and that also works. But when I fuse the two together.. That's where I am having issues. Also, the end of the text file is denoted by "#". Just so the break; makes sense.

#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();
}

Thanks for any input!

1
  • I just figured out what the program is getting hung up on. It is not sure what to do when sorting the data. It does not know if one word is greater than a different word. I am attempting to put this in alphabetical order so or instance if we had the three words dog, cat, fish. Dog would be the root node, cat would be the left child and fish would be the right child. Commented Mar 30, 2014 at 23:22

1 Answer 1

1

You need to return the newNode from GetNewNode.

Also, you should check for # before inserting the word, unless you want "#" in your tree.

Sign up to request clarification or add additional context in comments.

2 Comments

So one thing that I am unclear about is, how is it arranging the words? Do you think it is doing it alphabetically or does it do depending on the size of the word (bytes).
It is using the std::string's <= operator, so it would be alphabetical.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.