Advertisement
imashutosh51

Sum Tree

Jul 31st, 2022 (edited)
40
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 0.61 KB | None | 0 0
  1. int fun(Node *root,bool &ans){
  2.     if(!root) return 0;
  3.     if(!root->left && !root->right) return root->data;
  4.     int n1=0,n2=0;
  5.     n1=fun(root->left,ans);
  6.     n2=fun(root->right,ans);
  7.     if(n1+n2!=root->data) ans=false;    //ans will keep track for any position if not works,then ans =false else true
  8.     return n1+n2+root->data;
  9. }
  10. // Should return true if tree is Sum Tree, else false
  11. class Solution
  12. {
  13.     public:
  14.     bool isSumTree(Node* root)
  15.     {    if(!root || (!root->left && !root->right)) return true;
  16.          bool ans=true;
  17.          int temp=fun(root,ans);
  18.          return ans;
  19.     }
  20. };
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement