根节点应具有分配的节点,但仍为 NULL。为什么我无法将节点分配给根?
Root node should have an assigned node, but remains NULL. Why can't I assign a node to my root?
我正在以面向对象的格式编写二叉树。我以前有过二叉树的经验,但自从我触及这个以来已经有一段时间了。我的问题是我无法将节点分配给我的根。每次我检查调试模式时,根都保持为空。发生这种情况时,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&);
应该修复
当然实现标头也应该更改
相关文章:
- 预分配的节点向量中的无锁树节点分配
- 如何在 C++11 的内存池中分配 std::map 的内部RB_tree节点?
- nullptr = 节点分配不正确
- C++错误(从不兼容的类型"void"分配给树节点*)
- 根节点应具有分配的节点,但仍为 NULL。为什么我无法将节点分配给根?
- 将节点添加到链接列表中,而无需明确分配内存空间(无需使用新)
- 是否可以将新的列表节点分配给链表的现有节点
- 在声明节点创建链接列表时,为什么静态内存分配不起作用
- 将指针分配给链接列表节点会引发"Segmentation Fault"
- 如何从链表上的节点为分配的类释放内存
- 如何在速推中为节点分配标签
- 用C++在树中分配节点指针
- 关于在omnetpp.ini中将两个不同的应用程序随机分配到50个节点
- 递归后序遍历解除分配二叉树节点
- 分段 C++中链表节点分配的错误
- C++分配节点指针
- 我们需要为链表节点分配内存吗
- BinaryTree不会分配新创建的节点
- List Traversal w/temp指针-在声明指针时分配指针引用的节点空间有危险
- std::list如何分配节点和元素