Biggy
Biggy

Reputation: 15

C++ binary tree pointers issue

So i'm making a simple binary tree to store integers but I keep getting a "expression must have pointer-to-class type" error in the insert function, this is probably just me not noticing something obvious but I'm relatively new to C++ so any help would be appreciated. Thanks

struct node
{
    //Data stored in this node of the tree
    int data;
    //The left branch of the tree
    node *left;
    //The right branch of the tree
    node *right;
};

using namespace std;

//Inserts a value into the tree
void insert(node **tree, int value)
{
    if (*tree == nullptr)
    {
        //Create new node
        *tree = new node;
        //Set new value
        (*tree)->data = value;
        //Set branches to nullptr
        (*tree)->left = nullptr;
        (*tree)->right = nullptr;
    }
    else
    {
        if (value < (*tree)->data)
            insert(*tree->left, value);//ERROR HERE
        if (value >(*tree)->data)
            insert(*tree->right, value);//ERROR HERE
    }
}

//Deletes the tree
void delete_tree(node *tree)
{
    if (tree != NULL)
    {
        delete_tree(tree->left);
        delete_tree(tree->right);
        delete tree;
    }
}

//Prints the tree in order
void inorder(node *tree)
{
    if (tree != nullptr)
    {
            inorder(tree->left);
            cout << tree->data << " ";
            inorder(tree->right);
    }
}

int main(int argc, char **argv)
{
    while (true){
        //if(userinputflag=0)
        //else node *tree = input number
        node *tree = nullptr;

        while (true)
        {
            int num;
            cout << "Enter number (-1 to exit): ";
            cin >> num;

            if (num == -1)
                break;
            insert(&tree, num);
        }

        inorder(tree);
        cout << endl;

    }
}

Upvotes: 1

Views: 149

Answers (3)

kvorobiev
kvorobiev

Reputation: 5070

You function as first parameter requier pointer-to-pointer to node

void insert(node **tree, int value)

And here

insert(*tree->left, value);//ERROR HERE

which is not a valid.

I think you need something like this

insert(&((*tree)->left), value);//ERROR HERE

Upvotes: 1

Mahesh
Mahesh

Reputation: 34655

insert(*tree->left, value)

Operator -> has a higher precedence than *. The expression tree->left is syntactically wrong as tree type in the expression is node **. So, try -

insert(&((*tree)->left), value)

Upvotes: 1

Barry
Barry

Reputation: 303937

The signature of insert is:

void insert(node **tree, int value);

You are passing in *tree->left, which is *(tree->left), which is not a valid expression because tree is not a "pointer-to-class type", as the error suggests (it's a pointer-to-pointer-to-class).

What you had intended was (*tree)->left, which is a valid expression, but that would be a node* and our signature calls for a node**, hence:

insert(&((*tree)->left), value);

Upvotes: 1

Related Questions