Advertisement
prakharvk

replace a node with sum of its children

Jun 8th, 2019
87
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.07 KB | None | 0 0
  1. #include <bits/stdc++.h>
  2. using namespace std;
  3. class node{
  4.     public:
  5.     int data;
  6.     node *left;
  7.     node *right;
  8.     node(int d){
  9.         data=d;
  10.         left=NULL;
  11.         right=NULL;
  12.     }
  13. };
  14.  
  15.  
  16. node* buildTree(){
  17.     int data;
  18.     cin>>data;
  19.     if(data==-1)
  20.         return NULL;
  21.     node* curr=new node(data);
  22.     curr->left=buildTree();
  23.     curr->right=buildTree();
  24.     return curr;
  25. }
  26.  
  27. void print(node *root){
  28.     if(root==NULL)
  29.         return;
  30.     print(root->left);
  31.     print(root->right);
  32.     cout<<root->data<<" ";
  33. }
  34.  
  35. int replaceSum(node *root){
  36.     if(root!=NULL&&root->left==NULL&&root->right==NULL)
  37.         return root->data;
  38.     if(root==NULL)
  39.         return 0;
  40.     // if(root->left==NULL&&root->right==NULL)
  41.     //     return;
  42.     int temp=root->data;
  43.     int l=replaceSum(root->left);
  44.     int r=replaceSum(root->right);
  45.     root->data=l+r;
  46.     // int l=root->left ? root->left->data : 0;
  47.     // int r=root->right ? root->right->data : 0;
  48.     return root->data+temp;
  49. }
  50.  
  51. int main() {
  52.    
  53.     node *root=buildTree();
  54.     print(root);
  55.     replaceSum(root);
  56.     cout<<endl;
  57.     print(root);
  58.     return 0;
  59. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement