根节点应该有一个分配的节点,但保持NULL。为什么不能为根分配节点?

时间:2019-06-20 02:32:30

标签: c++ data-structures binary-tree

我正在以面向对象的格式编写二进制树。我以前有过使用二叉树的经验,但是自从接触到这已经有一段时间了。我的问题是我无法将节点分配给我的根。每次我在调试模式下检查时,根始终为NULL。发生这种情况时,cur节点将包含它分配的所有信息。

我尝试将root用户设为私有,并将this->root = NULL;更改为root-> = NULL;。我也尝试过将所有功能公开,但这并没有改变。我尝试将root的子级声明为NULL值,并将名称也声明为空字符串。

main.cpp

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

using namespace std;

int main() {
    string line;
    ifstream file;
    file.open("friends.txt");

    Friends f;

    while (getline(file, line)) {
        f.insert(f.root, line);
    }
    f.print(f.root);

    system("pause");
    return 0;
}

Friends.cpp

#include "Friends.h"
#include <iostream>
#include <string>

using namespace std;

Friends::Friends() {
    this->root = NULL;
}

Friends::node* Friends::createNode(string& val) {
    node* newNode = new node();
    newNode->left = NULL;
    newNode->right = NULL;
    newNode->name = val;
    return newNode;
}

Friends::node* Friends::insert(node* cur, string& val) {
    if (!cur) {
        cur = createNode(val);
    }
    else if (val < cur->name) {
        insert(cur->left, val);
        return cur;
    }
    else if (val > cur->name) {
        insert(cur->right, val);
        return cur;
    }
    return NULL;
}

void Friends::print(node* cur) {
    if (!cur) {
        return;
    }
    print(cur->left);
    cout << cur->name << endl;
    print(cur->right);
}

Friends.h

#ifndef FRIENDS_H
#define FRIENDS_H

#include <string>

using namespace std;

class Friends {
private:
    struct node {
        string name;
        node* left;
        node* right;
    };
public:
    node* root;
    node* insert(node* cur, string&);
    void print(node* cur);
    Friends();
    node* createNode(string&);
};

#endif

根节点应该有一个节点,但是一直显示为NULL值。它也不会运行任何错误。它只是保留为NULL

1 个答案:

答案 0 :(得分:1)

更改自:

node* insert(node* cur, string&);

至:

node* insert(node* &cur, string&);

应该修复

当然,实现标头也应该更改