# Replace node with sum of left and right subtree

Today’s problem is to replace node with sum of left and right subtree below node. By sum of children, we mean sum of all children of node and not just it’s immediate left and right child.
For example, consider binary search tree below,

Output should be as

Do you see the pattern here? What should be done before we process a parent node? Yes, we must process it’s left and right child first. And that’s post order traversal of tree. All we need to do is to replace print statement with addition of two nodes. Also, make sure we return sum of left, right and node itself, as parent node of current node will require that.

## Algorithm to replace node with sum of left and right subtree

```1. Start with root node.
2. If root is null return zero.
3. If there is left child, replace left child with sum of its children.
4. If there is right child, replace right child with sum of its children.
5. Replace root with sum of its right and left child.```
```#include<stdio.h>
#include<stdlib.h>
#include<math.h>

struct node{
int value;
struct node *left;
struct node *right;
};
typedef struct node Node;

int replaceNodeWithSumOfChildren(Node *root){
if (!root)
return 0;
int leftSum =  replaceNodeWithSumOfChildren(root->left);
int rightSum = replaceNodeWithSumOfChildren(root->right);

if(leftSum + rightSum != 0){
root->value = leftSum + rightSum;
}
return root->value;
}

void inorderTraversal(Node * root){
if(!root)
return;

inorderTraversal(root->left);
printf("%d ", root->value);
inorderTraversal(root->right);
}
Node *createNode(int value){
Node * newNode =  (Node *)malloc(sizeof(Node));
newNode->value = value;
newNode->right= NULL;
newNode->left = NULL;

return newNode;
}
if(node == NULL){
return createNode(value);
}
else{
if (node->value > value){
}
else{
}
}
return node;
}

/* Driver program for the function written above */
int main(){
Node *root = NULL;
//Creating a binary tree