(88). 27.8. SUM REPLACEMENT IN BINARY TREE - anishsingh90/Data_Structure_And_Algorithm_In_Cpp_github.io GitHub Wiki
//SUM REPLACEMENT IN BINARY TREE #include <bits/stdc++.h> using namespace std;
struct Node{ int data; struct Node* left; struct Node* right;
Node(int val){
data = val;
left = NULL;
right = NULL;
}
};
//Sum Replacement in Binary Tree void sumReplace(Node* root){ if(root == NULL){ return; }
sumReplace(root->left);
sumReplace(root->right);
if(root->left != NULL){
root->data += root->left->data;
}
if(root->right != NULL){
root->data += root->right->data;
}
}
//preorder function void preorder(Node* root){ if(root == NULL){ return; }
cout << root->data << " ";
preorder(root->left);
preorder(root->right);
}
int main(){ Node* root = new Node(1); root->left = new Node(2); root->right = new Node(3);
root->left->left = new Node(4);
root->left->right = new Node(5);
root->right->left = new Node(6);
root->right->right = new Node(7);
//Sum Replacement cout << "Preorder value: "; preorder(root); cout << "\n"; cout << "After Sum Replacement: "; sumReplace(root); preorder(root);
return 0;
}
/* OUTPUT: Preorder value: 1 2 4 5 3 6 7 After Sum Replacement: 28 11 4 5 16 6 7 */