Binary trees - general doubt

look at this piece of code that sir has used to mirror the binary tree,
void mirror(node* root) {
if (root == NULL)return;
swap(root->left, root->right);
mirror(root->left);
mirror(root->right);
return;
}
here, as i learnt in Linked lists, whenever we want to update the node pointers we use (node* &root) that means reference pointer, but in the above function we have not used it but still its giving the correct output? how is it happening? when I studied linked list and i asked this doubt 10 times and then i got it cleared but it came again. So can u pls explain properly

Hello @sktg99,

  1. Here you are passing the value to the function by a pointer. Watch video CPP - Pass by Reference Using Pointers.
  2. the root int the main function is a pointer variable that contains the address of the first node of the tree.
  3. When you execute mirror(root); in the main function. It sends the value stored in root i.e. the address of the first node.
  4. This address is then assigned to the root (another pointer variable local to the function).
  5. Similar is will happen with mirror(root->left); and mirror(root->right);
  6. As root in the mirror() function contains the address of the node, thus all the changes would be made in the memory directly.
  7. Hence, you are getting the desired result.

Let’s understand the basic but most important difference of between call by value and call by reference:

In call by value, you pass a value not the address of the variable in the main() function that contains the value. So, basically you are assigning this value to a new variable inside the function(i.e. a new address).

While in call by reference, you are passing the address instead. Now, as you are operating on the same address in both main() and function(). Hence, changes will persist.

Hope, this would help.
Give a like if you are satisfied.

1 Like