Binary Tree Sum Replacement

I have not understood how this code is error free.

  1. The function has a return type of ’ int ’
    However in the driver function , we have just called the function without assigning it to an integer variable.
  2. The function replaceSum(node *root) :
    is supposed to make change to the original tree.
    So how did this code work without passing the root by reference . Shouldn’t the code be
    int replaceSum(node *&root) ?
    How did the changes reflect?
    https://ide.codingblocks.com/#/s/22746
    line number : 160

@jaiskid , can you please help me out with this?
Thanks in advance.

@krishnamanohar199 hey krishna the reason is that to not passing with reference is we are not adding a new node or deleting node the existing node. we have already given tree we are changing value present inside the particular nodes of the given tree. I repeating we are not creating a new tree instead we are modifying a given tree.

1 Like

Alright, so if we dont append/delete the present structure, we dont need to pass that by reference?
I thought when a modification is being done , it must be passed by reference.

What about the return type of the function?

If you haven’t passed it by reference ,
it means that a copy has been created in the function and we are modifying the copy’s node data.
Then how is it being reflected in the actual program?

@krishnamanohar199 yes change will reflected in the actual program.basically it is like bhaiya create a instance of the tree and modified it but if bhaiya want to change in respect of structure he has pass by reference
remember two things
1 value can be change by creating copy of the given tree
2 structure of the tree will not change with the instance you have to use deep copy instead of the shallow copy

By structure I meant, the values of the data , sorry for the confusion :slight_smile: .
In the function , we have passed the root node.
Now a copy of the actual root has been created for the function. Whatever value I change in the function must pertain to the copy and must not reflect in the original root theoretically unless I pass it by reference, right?

@krishnamanohar199 yes it like you can create multiple copies of the tree and try different things with given tree without harming the original one.

Then how did the change reflect?
Is there an option to chat? Because this seems really confusing…

@krishnamanohar199 come on chat request

I’m sorry , how do I do that ?

@krishnamanohar199 there is chat request option in ask doubt portal

I have initiated one, is there anyone online ??

I hope I’ve cleared your doubt. I ask you to please rate your experience here
Your feedback is very important. It helps us improve our platform and hence provide you
the learning experience you deserve.

On the off chance, you still have some questions or not find the answers satisfactory, you may reopen
the doubt.