https://ide.codingblocks.com/s/227402 . why i dont get the required preorder
Please check the below code
hi @rohitkandpal683
question say that
replace each nodes’ data with the sum of all nodes’ which are greater or equal than it
but you have replace with greater element not sum of all greater element
i first traversl to right till it not become null because it is gretest among all them ,then i replace the root->data=r+p; where p is its own sum and r is its right sum. i replace the root->data becuse all nodes previous and left to it are smaller .
the expected output is 260 330 350 300 150 210 80 but my output comes 350 330 300 260 210 150 80
The first line contains a number n showing the length of the inorder array of BST. The next line contains n integers denoting the elements of the array.
so input is inorder bst
hence first you have bulid balanced BST from this input
then replace each node
and last print preorder
i solve this question correctly but by changing the return type i dont get right answer.void replace(node*root,int &sum) { if(root==NULL) { return ; } replace(root->right,sum); sum+=root->data; root->data=sum; replace(root->left,sum); }
can you please change the function code by changing return type from void to int
you make wrong tree
so how your output can be correct?
you have make skewed tree
but it should be balanced tree
50
/ \
30 70
/ \ / \
20 40 60 80
so
this is correct tree which you have to make
but your tree is not like that
your tree
10
20
30
40
50
60
70
80