Sum Tree | Practice | GeeksforGeeks

Given a Binary Tree. Return true if, for every node X in the tree other than the leaves, its value is equal to the sum of its left subtree's value and its right subtree's value. Else return false.
An empty tree is also a Sum Tree as the sum of an empty tree can be considered to be 0. A leaf node is also considered a Sum Tree.

Example 1:
Input:
    3
  /   \    
 1     2

Output: 1
Explanation:
The sum of left subtree and right subtree is
1 + 2 = 3, which is the value of the root node.
Therefore,the given binary tree is a sum tree.

Example 2:
Input:

          10
        /    \
      20      30
    /   \ 
   10    10

Output: 0
Explanation:
The given tree is not a sum tree.
For the root node, sum of elements
in left subtree is 40 and sum of elements
in right subtree is 30. Root element = 10
which is not equal to 30+40.

Your Task:  
You don't need to read input or print anything. Complete the function isSumTree() which takes root node as input parameter and returns true if the tree is a SumTree else it returns false.

Expected Time Complexity: O(N)
Expected Auxiliary Space: O(Height of the Tree)

Constraints:
1 ≤ number of nodes ≤ 104
+1
aryanmaurya3144 hours ago
class Solution{   private:   pair<bool, int> isSumTreeFast(Node* root){       // base case       if(root == NULL){           pair<bool, int> p = make_pair(true, 0);           return p;       }       // manage leaf nodes       if(root->left == NULL && root->right == NULL){           pair<bool, int> p = make_pair(true, root->data);           return p;       }              pair<bool, int> left = isSumTreeFast(root->left);       pair<bool, int> right = isSumTreeFast(root->right);              bool condition = root->data == left.second + right.second;              bool leftAns = left.first;       bool rightAns = right.first;              pair<bool, int> ans;              if(leftAns && rightAns && condition){           ans.first = true;           ans.second = 2*root->data;       }       else{           ans.first = false;       }       return ans;   }   public:   bool isSumTree(Node* root)   {        return isSumTreeFast(root).first;   }};
0
abhishekchauhan987920 hours ago
int sumTreeHelper(Node* root){
        if(root == NULL){
            return 0;
        }
        
        if(root->left==NULL and root->right==NULL){
            return root->data;
        }
        
        int leftsum = sumTreeHelper(root->left);
        int rightsum = sumTreeHelper(root->right);
        
        if(root->data != (leftsum + rightsum)){
            return 0;
        }
        return leftsum+rightsum+root->data;
    }
    bool isSumTree(Node* root)
    {
         // Your code here
         return sumTreeHelper(root);
    }
0
deathcloud3 days ago
Intuitive Easy and Efficient C++ Solution!
 
class Solution
{
    public:
    
    int helper(Node *root){
        if(root == NULL){
            return 0;
        }
        
        int ls = helper(root->left);
        int rs = helper(root->right);
        
        if(ls == -1 || rs == -1){
            return -1;
        }
        
        if(root->left == NULL && root->right == NULL){
            return root->data;
        }
        
        if(root->data != ls+rs)
            return -1;
        
        return ls + rs + root->data;
        
    }
    
    bool isSumTree(Node* root)
    {
         // Your code here
         int ans = helper(root);
         
         if(ans == -1)
            return false;
        else return true;
         
    }
};
0
nandasobhan6 days ago
can anyone suggest why all test cases are not passing for this code?
 
 
 
 
class Solution{   public:      int sumleft(Node*root){       if(root==NULL){           return 0;       }       if(root->left==NULL&&root->right==NULL){       return root->data;       }       return sumleft(root->left)+sumleft(root->right)+root->data;          }            int sumright(Node*root){        if(root==NULL){           return 0;       }       if(root->left==NULL&&root->right==NULL){       return root->data;       }       return sumleft(root->left)+sumleft(root->right)+root->data;   }      bool isSumTree(Node* root)   {        // Your code here        Node*curr=root;        if(root==NULL)        return true;         if(root->left==NULL&&root->right==NULL){       return true;       }        int suml=sumleft(root->left);        int sumr=sumright(root->right);        if(sumr+suml!=root->data){            return false;        }        else{            return true;        }   }};
0
alok016 days ago
class Solution{boolean isSumTree(Node root){            // Your code here            if(root==null)            {                return true;            }            if(root.left==null && root.right==null)            {                return true;            }            int l = sum(root.left);            int r = sum(root.right);                        if(l+r!=root.data)            {                return false;            }           return (isSumTree(root.left)&&isSumTree(root.right));             }int sum(Node root){    if(root==null)    {        return 0;    }    return sum(root.left)+sum(root.right)+root.data;}} 
-2
prateektripathi2 weeks ago
Looks like something wrong with 1 Test case
0
20ucs154
This comment was deleted.
-1
koulikmaity3 weeks ago
// { Driver Code Starts#include <bits/stdc++.h>using namespace std;
struct Node{   int data;   struct Node *left;   struct Node *right;};// Utility function to create a new Tree NodeNode* newNode(int val){   Node* temp = new Node;   temp->data = val;   temp->left = NULL;   temp->right = NULL;      return temp;}// Function to Build TreeNode* buildTree(string str){      // Corner Case   if(str.length() == 0 || str[0] == 'N')           return NULL;         vector<string> ip;      istringstream iss(str);   for(string str; iss >> str; )       ip.push_back(str);          // Create the root of the tree   Node* root = newNode(stoi(ip[0]));          // Push the root to the queue   queue<Node*> queue;   queue.push(root);          // Starting from the second element   int i = 1;   while(!queue.empty() && i < ip.size()) {                  // Get and remove the front of the queue       Node* currNode = queue.front();       queue.pop();                  // Get the current node's value from the string       string currVal = ip[i];                  // If the left child is not null       if(currVal != "N") {                          // Create the left child for the current node           currNode->left = newNode(stoi(currVal));                          // Push it to the queue           queue.push(currNode->left);       }                  // For the right child       i++;       if(i >= ip.size())           break;       currVal = ip[i];                  // If the right child is not null       if(currVal != "N") {                          // Create the right child for the current node           currNode->right = newNode(stoi(currVal));                          // Push it to the queue           queue.push(currNode->right);       }       i++;   }      return root;}
// } Driver Code Ends/*  Tree nodestruct Node{   int data;   Node* left, * right;}; */
// Should return true if tree is Sum Tree, else falseclass Solution{   public:   pair<bool,int> isSumTreeFast(Node* root)   {       // base case       if(root == NULL)       {           pair<bool,int>p = make_pair(true,0);           return p;       }              if(root->left == NULL && root->right == NULL )       {           pair<bool,int>p = make_pair(true,root->data);           return p;       }              pair<bool,int> leftAns = isSumTreeFast(root->left);       pair<bool,int> rightAns = isSumTreeFast(root->right);              bool left = leftAns.first;       bool right = rightAns.first;              bool condition = root-> data == leftAns.second + rightAns.second;              pair<bool,int>ans;       if(left && right && condition)       {           ans.first = true;           ans.second = leftAns.second + rightAns.second + root->data;       }       else       {           ans.first = false;       }       return ans;                 }   bool isSumTree(Node* root)   {        return isSumTreeFast(root).first;   }};
// { Driver Code Starts.
int main(){
   int t;scanf("%d ",&t);   while(t--)   {       string s; getline(cin,s);       Node* root = buildTree(s);       Solution ob;       cout <<ob.isSumTree(root) << endl;   }   return 1;}  // } Driver Code Ends
0
ashishsharma49793 weeks ago
C++ soln O(n)class Solution{   public:   int solve(Node* root,int& temp,int& sum,int& chk){       if(!root){           return 0;           }       if(!root->left && !root->right){           return root->data;       }       int l=solve(root->left,temp,sum,chk);       int r=solve(root->right,temp,sum,chk);       sum=l+r;       if(root->data!=sum){           chk=0;       }       else{           root->data+=sum;       }       return root->data;   }   bool isSumTree(Node* root)   {       int temp=0;       int sum=0;       int chk=true;       solve(root,temp,sum,chk);       return chk;        // Your code here   }};
-1
sachinsinghss193 weeks ago
#Python solution using dfs O(n^2) 
 
def isSumTree(self,root):       # Code here       def getSum(root:Node):           if not root:               return 0                      return root.data + getSum(root.left) + getSum(root.right)              def dfs(root:Node):                  if not root:               return True                      sm = True           if root.left and root.right:               sm = ((getSum(root) - root.data) == root.data)                          return sm and dfs(root.left) and dfs(root.right)              return dfs(root)
We strongly recommend solving this problem on your own before viewing its editorial. Do you still
                    want to view the editorial?
 Login to access your submissions. 

Problem


Contest

Reset the IDE using the second button on the top right corner.
Avoid using static/global variables in your code as your code is tested against multiple test cases and these tend to retain their previous values.
Passing the Sample/Custom Test cases does not guarantee the correctness of code. On submission, your code is tested against multiple test cases consisting of all possible corner cases and stress constraints.
You can access the hints to get an idea about what is expected of you as well as the final solution code.
You can view the solutions submitted by other users from the submission tab.