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. 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);
}
CodePudding user response:
#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. And root to be initialized by result of CreateNode
function.