[英]binary search tree by smart pointers
I used row pointers to implement the binary search tree data structure and it worked perfectly, but when I replaced the row pointers with shared_ptr it compiles successfully but the program crashes due to unknown run-time error.我使用行指针来实现二叉搜索树数据结构,它工作得很好,但是当我用 shared_ptr 替换行指针时,它编译成功,但由于未知的运行时错误,程序崩溃了。 Could you please help in this?
你能帮忙吗?
#include<iostream>
#include<memory>
class node{
public:
int data;
std::shared_ptr<node>left = std::make_shared<node>();
std::shared_ptr<node>right = std::make_shared<node>();
};
std::shared_ptr<node>CreateNode(int x);
void print_tree(const std::shared_ptr<node>&x);
int main(){
auto root = std::make_shared<node>();
root = CreateNode(12);
root->left = CreateNode(9);
root->right = CreateNode(14);
root->left->right = CreateNode(10);
root->left->right = CreateNode(11);
print_tree(root);
return 0;
}
std::shared_ptr<node>CreateNode(int x){
std::shared_ptr<node>NewNode = std::make_shared<node>();
NewNode->data = x;
NewNode->left = NewNode->right = nullptr;
return NewNode;
}
void print_tree(const std::shared_ptr<node>&x){
if(x==nullptr) return;
std::cout<<x->data<<std::endl;
print_tree(x->left);
print_tree(x->right);
}
#include<iostream>
#include<memory>
class node
{
public:
int data;
std::shared_ptr<node>left;
std::shared_ptr<node>right;
};
std::shared_ptr<node>CreateNode(int x);
void print_tree(const std::shared_ptr<node>&x);
int main()
{
auto root = CreateNode(12);
root->left = CreateNode(9);
root->right = CreateNode(14);
root->left->right = CreateNode(10);
root->left->right = CreateNode(11);
print_tree(root);
return 0;
}
std::shared_ptr<node>CreateNode(int x)
{
std::shared_ptr<node>NewNode = std::make_shared<node>();
NewNode->data = x;
NewNode->left = NewNode->right = nullptr;
return NewNode;
}
void print_tree(const std::shared_ptr<node>&x)
{
if(x==nullptr) return;
std::cout<<x->data<<std::endl;
print_tree(x->left);
print_tree(x->right);
}
This works on my machine.这适用于我的机器。 I made
left
and right
pointers in node
class initially equal to nullptr
, instead of creating new node because you can't know is it going to be used.我在
node
类right
left
最初等于nullptr
,而不是创建新节点,因为你不知道它是否会被使用。 And root to be initialized by result of CreateNode
function.根由
CreateNode
函数的结果初始化。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.