二叉树插入功能无法正常工作C ++

时间:2013-11-16 06:50:50

标签: c++ binary-tree binary-search-tree

我正在开发一个使用二叉树的程序。程序从文本文件中读取,按字母顺序将每个单词存储在二叉树中,并查找该单词出现在文件中的次数。

我遇到的问题是我的插入功能不起作用(程序在尝试运行时崩溃)。我不知道究竟是什么错误,但我怀疑它与我的else语句有关,该函数结束了处理树右侧的函数。

任何帮助修复它都将不胜感激。

标头文件

#include <iostream>
#include <string>

using namespace std;

#ifndef TREE_H
#define TREE_H

class Tree
{
public:
    Tree();
    Tree(string str);
    void traversal (Tree *);
    void read_file();
    void insert(string str);
    ~Tree();
private:
    Tree *left;
    Tree *right;
    string word;
    int count;
};

#endif // TREE_H

Cpp文件

#include <iostream>
#include <string>
#include <fstream>
#include "tree.h"

using namespace std;

Tree::Tree()
{ 
    left = NULL;
    right = NULL;
    count = 0;
}

Tree::Tree(string s)
{
    word = s;
}

Tree::~Tree() { }

void Tree::read_file()
{
    ifstream myfile;
    myfile.open("input.txt", ios::out | ios::in | ios::binary);
    if(myfile.is_open()){
        while(myfile.good()) {
            string buffer;
            while(true) {
                char c = myfile.get();
                if(c == '-' || c == '\'' || isalpha(c) ){
                    if(isupper(c)) c = tolower(c); 
                    buffer+=c;
                }
                else break;
            }
            if(buffer.length() >= 4){
                insert(buffer);
            }
        }
    myfile.close();
    traversal(this);
    }
    else { cout << "Unable to open file!" << endl; }
}

void Tree::insert(string str) {
    if(str.empty()){  // Also I'm debating whether I need this or not since the string
                      // cannot possibly be empty as it's part of the condition before                     
                      //insert is even called.
        this->word = str;
        count++;
    }
    else if(this->word == str) count++;
    else if(str < this->word){
        if(this->left == NULL) this->left = new Tree(str);
        else this->left->insert(str);
    }
    else {
        if(this->right == NULL) this->right = new Tree(str);
        else this->right->insert(str);
    }
}

void Tree::traversal(Tree *T) {
    if(T != NULL) {
        traversal(T->left);
        cout << T->word << " (" << count << ")" << endl;
        traversal(T->right);
    }
}

主要

#include <iostream>
#include "tree.h"

using namespace std;

int main()
{
    Tree tree;
    tree.read_file();
    return 0;
}

2 个答案:

答案 0 :(得分:2)

问题是你有2个构造函数,第二个没有将指针左/右初始化为NULL。

编辑您正在显示来自不同对象的属性:使用

cout << T->word << " (" << T->count << ")" << endl;

因为递归过程不能调用收到的T的成员函数。你可以静态,或改变它

void Tree::traversal() {
    if(this) {
        traversal(left);
        cout << word << " (" << count << ")" << endl;
        traversal(right);
    }
}

就个人而言,我更喜欢这种最后的'风格'。

答案 1 :(得分:0)

Tree::Tree()
{ 
    word.clear();
    left = NULL;
    right = NULL;
    count = 0;
}

Tree::Tree(string s)
{
    word = s;
    left = NULL;
    right = NULL;
    count = 0;
}