inline void insert(node *root, int value)
{
if(!root)
{
root = new node();
root->value = value;
}
else
{
node *itr = root;
while(1)
{
if(itr->value > value)
itr = itr->left;
else
itr = itr->right;
if(!itr)
{
itr = new node();
itr->value = value;
break;
}
}
}
}
//call insert function like this
node *head = 0;
insert(head, 5);
insert(head, 10);
insert(head, 3);
insert(head, 1);
insert(head, 4);
I know this code wouldn’t work because ‘itr’ in insert function is a local variable, thus, it wouldn’t reflect the tree outside of the method.
However, I don’t clearly understand why it wouldn’t work.
Although ‘itr’ is a local variable, ‘itr’ points to the same location where ‘root’ points to. Also, I am dereferencing it to move ‘left’ or ‘right’ so I think it should work.
I think this is a basic problem of passing a pointer by value vs pointer but I couldn’t find a clear explanation of why I can’t change the tree using a local variable of a pointer.
Suppose you had
Would you expect that x also contain
3478?I knew you wouldn’t, and the same is true for your
rootanditr.This is a classic pencil-and-paper problem (most pointer problems are) and it’s definitely worth pulling out some dead tree when you run into problems like this.
Here’s an ASCII version for one of your cases, where you want to insert to the right, and right is NULL.
The arrows show where the respective variables are pointing.
Start of function:
As you can see, the input tree hasn’t been modified at all, you just allocated a new node outside of it and left it there.
This would work:
Pencil and paper is the best way to figure out pointers.