二叉搜索树在C++中的实现
Binary Search Tree implementation in C++
#include <iostream>
using namespace std;
class Node{
public:
int data;
Node* left_child;
Node* right_child;
Node(int x){
data = x;
left_child = NULL;
right_child = NULL;
}
};
class BST{
public:
//Initially root is null
Node* root = NULL;
void insert(Node* node, int data){
if(node == NULL){
node = new Node(data);
return;
}
if(data < node->data){
insert(node->left_child,data);
}
else if(data > node->data){
insert(node->right_child,data);
}
}
void just_insert(int data){
insert(root,data);
}
void print(Node* node){
if(node == NULL){
return;
}
cout<<node->data<<" ";
print(node->left_child);
print(node->right_child);
}
void just_print(){
print(root);
}
};
int main() {
//For fast IO
ios_base::sync_with_stdio(false);
cin.tie(NULL);
int n,x;
cin>>n;
BST bst = BST();
for(int i=0; i<n; i++){
cin>>x;
bst.just_insert(x);
}
bst.just_print();
return 0;
}
BST的这种实现有什么问题?我给出 8 个值作为输入:835168724但是当我调用打印函数时。我没有得到任何输出。我错过了一些指针逻辑吗?insert 函数以递归方式沿着树向下移动,以查找插入值的位置打印函数也可以递归工作。
让我们看一下 insert
函数中的这些行:
if(node == NULL){
node = new Node(data);
return;
}
这里的问题是参数node
是按值传递的,就像任何其他局部变量一样,并且像任何其他局部变量一样,一旦函数返回,它就会超出范围,并且对变量的所有更改都将丢失。
你需要通过引用传递指针,比如
void insert(Node*& node, int data){ ... }
// ^
// Note ampersand here
您永远不会在 BST 类中分配给 root,因为您对插入类中节点的赋值在插入函数之外不可见。您可以通过引用插入函数来传递 Node 指针来解决此问题:
void insert(Node*& node, int data)
相关文章:
- 如果没有malloc,链表实现将失败
- 如何在c++中实现处理器调度模拟器
- 如何在c++中使用引用实现类似python的行为
- 实现无开销push_back的最佳方法是什么
- 使用简单类型列表实现的指数编译时间.为什么
- 如何在BST的这个简单递归实现中消除警告
- 实现一个在集合上迭代的模板函数
- 我应该实现右值推送功能吗?我应该使用std::move吗
- 如何正确实现和访问运算符的各种自定义枚举器
- C++Union/Struct位域的实现和可移植性
- 这个极客对极客的trie实现是否存在内存泄漏问题
- 在c++中实现LinkedList时,应出现未处理的错误
- 为左值和右值的包装器实现C++范围
- 使用模板进行堆栈实现; "name followed by :: must be a class or namespace"
- 使用GSoap实现ONVIF
- 在用于格式4的arm模拟器中实现功能时的一个问题
- 用于AVX的ln(x)的实现,m256
- 用常见虚拟函数实现的任意组合来实现派生类的正确方法是什么
- 在C++中,如何在类和函数(可能是模板化的)的头中编写完整的实现
- std::random_device是如何实现的