DEV Community

Quoc Bao
Quoc Bao

Posted on • Updated on

Binary Search Tree Class Implementation

Hello everybody! Today, I will show you an implementation of the binary search tree (BST) class which borrows the structure of a linked list but is a little bit different. The BST has two reference fields (left subtree and right subtree) instead of just only one. Though I have implemented a linked list class before, it has not quite come as an official post. Therefore, if you want to compare between the two, see it for yourself.

Without further ado, let’s get on!

struct node
{
    int info;
    node *left;
    node *right;
};

class BST
{
private:
    node *root;
    void deepcopy(const BST &other);

public:
    // node *search(int);
    // node *search(node *, int);
    BST();
    ~BST();
    BST(int);
    BST(const BST &other);
    BST &operator=(const BST &other);
    void insert(int);
    void insert(node *, int);
};
Enter fullscreen mode Exit fullscreen mode

Read more here!

Top comments (2)

Collapse
 
tandrieu profile image
Thibaut Andrieu

Hi !

Glad to see that some still accord importance to data structure πŸ˜€
I advice you to replace naked pointer (aka node*) by smart pointer like std::shared_ptr. The small overhead introduced by smart ptr is largely counterbalanced by the better and easier memory management you will gain.

You save time by not handling crazy memory issues => you have more time to do real optimization to your algorithm => your program runs faster.

Collapse
 
qbaocaca profile image
Quoc Bao

Thank you very much for your advice. I am still a student and have much to learn <3