【问题标题】:Root node should have an assigned node, but remains NULL. Why can't I assign a node to my root?根节点应该有一个分配的节点,但保持为 NULL。为什么我不能将节点分配给我的根?
【发布时间】:2019-06-20 02:32:30
【问题描述】:

我正在编写面向对象格式的二叉树。我以前有过使用二叉树的经验,但是我已经有一段时间没有接触到这个了。我的问题是我无法将节点分配给我的根。每次我在调试模式下检查时,根都保持为 NULL。在此过程中,cur 节点包含它分配的所有信息。

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

ma​​in.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

【问题讨论】:

  • 您需要传递对指针的引用,而不是副本。
  • 显示的代码分配给 root 的唯一值是 NULL,所以这就是你在这里看到的全部。显然插入逻辑是有缺陷的。没有给根分配其他任何东西。
  • 在插入中传递 f.root 的副本,然后当它为 NULL 时,您将新节点分配给副本。你永远不会改变原来的。就像@RetiredNinja 所说:您需要传递对指针的引用,而不是副本。
  • @SamVarshavchik 但f.insert(f.root, line); 不应该这样做吗?
  • @chipster - 将某些内容分配给“cur”,这是该函数的参数。仅仅因为某处的一些其他变量作为参数传递给该函数并不意味着原始变量也将被分配给。这不是 C++ 的工作方式。为此,cur 必须是参考。不是。

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


【解决方案1】:

更改自:

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

到:

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

应该修复

当然实现头也要改

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2019-09-19
    • 2023-03-25
    • 2013-12-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多