今天,我了解了二叉搜索树,我正在尝试实现它,但我遇到了一个问题。
假设我有这样的Struct
:
struct Node {
int v;
Node* left = NULL;
Node* right = NULL;
}
在它下面,我有:
// At the beginning, root is NULL
Node* root = NULL;
Node* new_node(int v) {
Node* n = new Node;
n->v = v;
return n;
}
void insert(int v) {
// At the beginning, root is NULL
Node* c = root;
while (c != NULL) {
if (v < c->v) {
c = c->left;
} else {
c = c->right;
}
}
c = new_node(v);
}
在主代码中,我使用以下代码测试了我的实现:
int main() {
insert(5);
}
当我使用insert(5)
时,在insert
函数中,变量c
会root
,并且因为当时root
是NULL
,所以c
等于new_node(v)
。但是当我打印root->v
时,它什么也没返回。
我做错了什么吗??
在代码中,初始化后不会修改root
。root
总是NULL
.这
Node* c = root;
// ...
c = new_node(v);
不会改变root
.它只是声明一个局部变量c
,用root
的值初始化它,并给它分配一个新值。
如果你想改变函数中某物的值,你可以通过引用传递它,指针在这方面没有什么不同。例如:
#include <iostream>
struct Node {
int v;
Node* left = NULL;
Node* right = NULL;
};
Node* root = NULL;
Node*& find_insertion(Node*& ptr, int v){
if (ptr == NULL) return ptr;
if (v < ptr->v) {
return find_insertion(ptr->left,v);
} else {
return find_insertion(ptr->right,v);
}
}
void insert_at(Node*& ptr,int v){
Node*& insertion = find_insertion(root,v);
insertion = new Node;
insertion->v = v;
}
void insert(int v){
insert_at(root,v);
}
int main() {
insert(5);
std::cout << root->v;
}
接下来,您应该查看智能指针(std::unique_ptr
),以避免泄漏或编译手动内存管理。