c++ - 二叉树插入方法C++
问题描述
struct node {
person * data;
node * left, * right;
node(person * p) {
data = p; left = NULL; right = NULL;
}
};
class tree {
protected:
node * root;
public:
tree() {
root = NULL;
}
tree(person * p) {
root = new node(p);
}
void insert(person * p) {
if(root == NULL) {
root = new node(p);
return;
}
node * curr = root;
while(true) {
if(p->last < curr->data->last) {
if(curr->left == NULL) {
curr->left = new node(p);
return;
}
curr = curr->left;
} else {
if(curr->right == NULL) {
curr->right = new node(p);
return;
}
curr = curr->right;
}
}
}
void insert(node * & n, person * p) {
if(n == NULL) {
n = new node(p);
return;
}
if(p->last < n->data->last)
insert(n->left, p);
else
insert(n->right, p);
}
void insert(person * p) {
insert(root, p);
}
void print(node * n) {
if(n == NULL)
return;
print(n->left);
cout << n->data->ss << " " << n->data->bday << " "<< n->data->first << ", " << n->data->last << " " << n->data->zip << "\n";
print(n->right);
}
void print() {
print(root);
}
};
我查看了 BST 插入的其他实现,我的逻辑遵循我见过的其他线程。在构造函数中将 Root 设置为 NULL 当我使用 print 函数时,它会打印出随机值,而不是与 person 类型一起存储的信息。在我的代码中,我尝试了两种插入方法。我还包括了我的打印功能,以防出现问题。我从打印功能返回的打印输出几乎看起来像是显示内容的内存地址,但缺少一些信息。我不知道从这里去哪里。
解决方案
I found what the problem was. In my person struct, I was naming the parameters of the constructor the same as the variables in the struct. Apparently c++ doesn't like when that's done. Changing the names of the constructor parameters to something else fixed the problem.
Old:
person(int ssn, int bday, string first, string last, int zip) {
ssn = ssn; bday = bday; first = first; last = llast; zip = zip;
}
New:
person(int s, int b, string f, string l, int z) {
ssn = s; bday = b; first = f; last = l; zip = z;
}
推荐阅读
- laravel - Chrome 扩展获取功能不发送 cookie
- python-3.x - Python Seaborn:如何在箱线图可视化中添加均值?
- fortran - Fortran77 程序不执行
- firefox - Firefox Container Tabs 和 Microsoft Teams:我应该将哪些域添加到容器中?
- vue.js - 导航上的 Vue url 更改
- javascript - Web midi API 和多个同步笔记
- ios - 如何使用 Xcode 模拟海拔?
- assembly - 如何在裸机 ARM 组件中使用键盘?
- php - PHP 的 `mysqli_connect()` 返回什么类型的对象?
- google-apps-script - Gmail插件中的多行TextInput高度