Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <bits/stdc++.h>
- using namespace std;
- class node{
- public:
- int data;
- node *left;
- node *right;
- node(int d){
- data=d;
- left=NULL;
- right=NULL;
- }
- };
- node* buildTree(){
- int data;
- cin>>data;
- if(data==-1)
- return NULL;
- node* curr=new node(data);
- curr->left=buildTree();
- curr->right=buildTree();
- return curr;
- }
- void print(node *root){
- if(root==NULL)
- return;
- print(root->left);
- print(root->right);
- cout<<root->data<<" ";
- }
- int replaceSum(node *root){
- if(root!=NULL&&root->left==NULL&&root->right==NULL)
- return root->data;
- if(root==NULL)
- return 0;
- // if(root->left==NULL&&root->right==NULL)
- // return;
- int temp=root->data;
- int l=replaceSum(root->left);
- int r=replaceSum(root->right);
- root->data=l+r;
- // int l=root->left ? root->left->data : 0;
- // int r=root->right ? root->right->data : 0;
- return root->data+temp;
- }
- int main() {
- node *root=buildTree();
- print(root);
- replaceSum(root);
- cout<<endl;
- print(root);
- return 0;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement