I have a binary tree that looks like this
struct Node
{
int key;
double data;
Node* right;
Node* left;
};
and I have this "insert" function for inserting new nodes and building the tree
void insert(Node*& p, int key, double to_be_inserted)
{
if (p == nullptr)
{
p = new Node;
p->key = key;
p->data = to_be_inserted;
p->left = nullptr;
p->right = nullptr;
}
else
{
if (p->key == key)
{
p->data = to_be_inserted;
}
else
{
Node*& child = (p->key > key) ? p->left : p->right;
insert(child, key, to_be_inserted);
}
}
}
and a main function that looks like this
int main(int argc, char ** argv)
{
Node* root = nullptr;
insert(root, 11, 11);
insert(root, 6, 6);
insert(root, 4, 4);
insert(root, 5, 5);
insert(root, 8, 8);
insert(root, 10, 10);
insert(root, 19, 19);
insert(root, 17, 17);
insert(root, 43, 43);
insert(root, 31, 31);
insert(root, 49, 49);
printTree(root, 0);
return 0;
}
The final "printed-out" tree looks like this
(This "print-out" is meant to be read from left to right instead of top to bottom)
My questions are:
How does the
insertfunction know what the tree currently looks like when it's being called a second (or more) time?rootin main is just a single node (with two children) that is not changing(according to my debugger) and you're using the samerootas argument multiple times. How does it know where it left off wheninsertis called again? What is thep = new Nodeline actually doing (ininsert). Seems to me that it is just overwriting root, over and over again? Basically, where does it store the memory of what the (current) full tree looks like?Would the
insertfunction behave differently if it was declared asNode * insert(Node * p, int key, double value);?Is there a specific reason why
pis a pointer reference instead of a normal pointer? What's the difference?
Sorry, for the long (and possibly stupid) questions. I am new to C++. I understand the basics of pointers and references but apparently I can't really seem to figure out what is actually happening in the insert function (and in the main function, when insert is being called multiple times with the SAME root parameter).
Thanks!
