Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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. 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);
}

>Solution :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

#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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading