根节点应具有分配的节点,但仍为 NULL。为什么我无法将节点分配给根?

Root node should have an assigned node, but remains NULL. Why can't I assign a node to my root?

本文关键字:分配 节点 为什么 根节点 NULL      更新时间:2023-10-16

我正在以面向对象的格式编写二叉树。我以前有过二叉树的经验,但自从我触及这个以来已经有一段时间了。我的问题是我无法将节点分配给我的根。每次我检查调试模式时,根都保持为空。发生这种情况时,cur 节点包含为其分配的所有信息。

我尝试将我的根设为私有并将this->root = NULL;更改为root-> = NULL;。我也尝试公开我的所有功能,但没有区别。我尝试将 root 的子项声明为 NULL 值,并将名称声明为空字符串。

主.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;
}

朋友.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);
}

朋友.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.

更改自:

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

自:

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

应该修复

当然实现标头也应该更改