根节点应该有一个分配的节点,但保持为NULL.为什么不能为根分配节点? [英] Root node should have an assigned node, but remains NULL. Why can't I assign a node to my root?
问题描述
我正在以面向对象的格式编写一个二叉树.我以前有过使用二叉树的经验,但是自从接触到这已经有一段时间了.我的问题是我无法将节点分配给我的根.每次我在调试模式下检查时,其根始终为NULL.发生这种情况时,cur节点将包含它分配的所有信息.
I'm writing a binary tree in object-oriented format. I've had experience with binary trees before, but it's been a while since I've touched on this. My problem is that I'm unable to assign a node to my root. Every time I check in debugging mode, the root remains NULL. While this is happening, the cur node contains all the information it's assigned.
我尝试将我的根目录设为私有,并将this->root = NULL;
更改为root-> = NULL;
.我也尝试过将所有功能公开,但这并没有改变.我尝试将root的子级声明为NULL值,并将名称也声明为空字符串.
I've tried making my root private and changing this->root = NULL;
to root-> = NULL;
. I've also tried making all of my functions public, but it didn't make a difference. I tried declaring root's children to NULL values and name to an empty string as well.
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
.
The root node should have a node, but has keeps showing up as a NULL
value. It doesn't run with any errors either. It just remains as NULL
.
推荐答案
更改自:
node* insert(node* cur, string&);
至:
node* insert(node* &cur, string&);
应该修复
当然,实现标头也应该更改
Of course the implementation header should also be changed
这篇关于根节点应该有一个分配的节点,但保持为NULL.为什么不能为根分配节点?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!