0

I am trying to implement a simple Binary search tree but I have got some problems, I can't figure out what's the problem here.

#include<bits/stdc++.h>
using namespace std;

class Node{
public:
    int data;
    Node* left = NULL;
    Node* right = NULL;

    Node(int x):data(x)
    {}
};

//BST Extends the Node class
class BST : public Node{
public:
    Node* root = NULL;
    //basic operations
    void insertion(Node* root, int x);
    void preorder(Node* root);
};

void BST::insertion(Node* root, int x) {
    Node* newNode = new Node(x);
    if(!root) {
    root = newNode;
    return;
    }
    if(x > root->data) BST::insertion(root->right, x);
    if(x < root->data) BST::insertion(root->left, x);
}

void BST::preorder(Node* root) {
    if(!root) return;

    cout << root->data << " ";
    BST::preorder(root->left);
    BST::preorder(root->right);
}

int main() {
    BST tree;
    tree.insertion(tree.root, 8);
    tree.insertion(tree.root, 6);
    tree.insertion(tree.root, 12);
    tree.insertion(tree.root, 10);
    tree.preorder(tree.root);
    return 0;
   }

These are the errors:

BST.cpp:46:6: error: use of deleted function 'BST::BST()'
BST tree;
      ^~~~
BST.cpp:17:7: note: 'BST::BST()' is implicitly deleted because the default definition would be ill-formed:
 class BST : public Node{
       ^~~
BST.cpp:17:7: error: no matching function for call to 'Node::Node()'
BST.cpp:12:2: note: candidate: 'Node::Node(int)'
  Node(int x):data(x)
  ^~~~
BST.cpp:12:2: note:   candidate expects 1 argument, 0 provided
BST.cpp:6:7: note: candidate: 'constexpr Node::Node(const Node&)'
 class Node{
       ^~~~
BST.cpp:6:7: note:   candidate expects 1 argument, 0 provided
BST.cpp:6:7: note: candidate: 'constexpr Node::Node(Node&&)'
BST.cpp:6:7: note:   candidate expects 1 argument, 0 provided

I checked few answers but unable to figure out the causing problem here, I am thinking it is the problem with the constructor and data members

ashirbad29
  • 19
  • 5

1 Answers1

1

You did not give your root node a value.

A BST is a Node, and Node's only constructor expects an int val. There is no default constructor — it's been inhibited or, in C++ terminology, "deleted".

You need to give BST a similar constructor to pass that along to Node (or write using Node::Node to inherit it), and your declaration of tree in main needs to provide a value.

Asteroids With Wings
  • 16,164
  • 2
  • 17
  • 33
  • sorry, I am unable to understand what you mean by _giving `BST` a similar constructor_, please clarify – ashirbad29 May 20 '20 at 10:14
  • It would need a `BST(int x) : Node(int x)` .. though, looking more closely, I'm not convinced you want `BST` to _be_ a `Node`, since it _contains_ its root node. Perhaps just remove the inheritance instead? – Asteroids With Wings May 20 '20 at 11:26