Help with approach

problem: https://hack.codingblocks.com/app/contests/2022/459/problem

sol: https://ide.codingblocks.com/s/418705

although it is not working this is what I have thought and implemented:

calculate sum or right subtree and root and substitute the value of root->left with it

root = sum of right subtree

root -> right = sum of it’s right subtree

please guide where this is wrong

Logic is correct just wrong implementation Try to do it somewhat like this

void replacenode(node* root,int *sum)
{
	if(root==NULL)
	{
		return ;
	}
	replacenode(root->right,sum);
	*sum=*sum + root->data;
	root->data=*sum;
	replacenode(root->left,sum);

}

I’m not able to understand the reason for using the pointer in int* sum

Have used Call by reference method , in which when i call function from main function replacenode(root,sum) where sum is initialised with 0.

oh okay it’s the same as doing &sum right?

Yes … It’s same, do you want me to share code for your reference purposes ?


I wrote it but it is giving the wrong the answer

Hey , I miss understood the question. It’s somewhat like this


There inout and output format isn’t even clear to me so inwould suggest you to understand the logic from here, read the documentation, if found any difficulty in understanding, feel free to ask. Although it will be easy for you to understand.

yeah I implemented using that way only by doing the reverse inorder and changing values, but there is some bug which is giving the wrong output

the article’s way and your way are same so you were right I guess?

I’ll suggest you to ask the same question by making a new thread to make sure if the logic i told to you is right or not. Cause i am also confused in this question. You can also reopen this doubt. Also have made change in your build function, now it’s making your tree perfectly

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.