No output.What is the error?
Hello @shivansh.sm1,
-
The way you have build the BST is wrong for this problem.
The middle element of the input sequence is the root of the BST.
All elements on left of that element are nodes of left subtree.
and all elements on right of that element are nodes of right subtree. -
The reason of no output is incorrect statements in the base condition of the insertAtBST.
Correction:
if(root==NULL){
// return NULL;
root=new node(d);
return root;
} -
The logic of sumreplace() function is also wrong.
Hint:
Postorder of the BST.
Think how you can use the post-order to solve this problem.
Hope, this would help.
Give a like if you are satisfied.
please explain logic for sumreplace()
Sure @shivansh.sm1,
As you have to replace the value of a node with the sum of all the nodes larger to it include the value of that node.
In BST all values larger to a particular node are the part of itβs right most subtree.
So, the rightmost element will be the largest one.
Therefore, when you do postorder traversal of the BST.
You first go to the largest element and then return to next smaller element.
This way you can access the node is decresing order while returning from a particular node.
//Logic:
void replaceSum(node* &root){
static int sum=0;
if(root==NULL)
return;
replaceSum(root->right);
sum+=root->data;
root->data=sum;
replaceSum(root->left);
}
Hope, this would help.