The below is my code for inserting elements into a Binary Search Tree. The insert function has two parameters, value which is the number to be inserted into the tree and root, which is the root of tree.
My root->getLeft()
and root->getRight()
both return a BinaryNode*
, which is why I'm thinking its returning this error:
BST.cpp: In function ‘void insert(int, BinaryNode*&)’:
BST.cpp:72:34: error: invalid initialization of non-const reference of type ‘BinaryNode*&’ from an rvalue of type ‘BinaryNode*’
void insert(int value, BinaryNode*& root) {
cout << "Looping" << endl;
if(root == NULL) {
BinaryNode* node = new BinaryNode(value);
root = node;
cout << "finalized" << endl;
cout << "Root value: " << root->getValue() << endl;
}
else if(value < root->getValue()) {
insert(value, root->getLeft());
cout << "went to left" << endl;
}
else if(value >= root->getValue()) {
insert(value, root->getRight());
cout << "went to right" << endl;
}
}
How would I modify root->getLeft()
so that the right value (*&) is passed in?
Additionally, what exactly does *& mean? I've been testing only passing in BinaryNode*
root and the changes to root never seem to take effect, e.g. root forgets its value outside of insert and in the past only *& has seemed to work to change the actual value of the original.
Thanks!