Given the root of a Binary Tree with n nodes, check whether it is a Sum Tree and return true if it is, otherwise return false.
A Sum Tree is a Binary Tree in which the value of every non-leaf node is equal to the sum of all nodes present in its left and right subtrees. An empty tree and a leaf node are also considered Sum Trees.
Example:
Input: root[] = [3, 1, 2] Output: true 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.
Input: root[] = [10, 20, 30, 10, 10] Output: false Explanation: The given tree is not a Sum Tree. For the root node, the sum of nodes in the left and right subtrees is 40 + 30 = 70, which is not equal to the root value 10.
[Naive Approach] By Checking Every Node - O(n^2) Time and O(h) Space
The idea is to get the sum of the left subtree and right subtree for each node and compare it with the node's value. Also recursively check if the left and right subtree are sum trees or not.
If the current node is NULL or a leaf node, return true since it is a Sum Tree.
Recursively compute the sum of all nodes in the left subtree.
Recursively compute the sum of all nodes in the right subtree.
Check whether the current node's value equals the sum of the left and right subtree sums.
Recursively verify that both the left and right subtrees are also Sum Trees.
Return true only if the current node satisfies the Sum Tree property and both subtrees are Sum Trees; otherwise, return false.
C++
#include<iostream>usingnamespacestd;classNode{public:intdata;Node*left,*right;Node(intx){data=x;left=right=nullptr;}};// Returns the sum of all nodes in the subtree rooted at 'root'.intsum(Node*root){if(root==nullptr)return0;returnroot->data+sum(root->left)+sum(root->right);}// Returns true if the binary tree rooted at 'root' is a Sum Tree.boolisSumTree(Node*root){// An empty tree and a leaf node are always Sum Trees.if(root==nullptr||(root->left==nullptr&&root->right==nullptr))returntrue;// Calculate the sum of nodes in the left and right subtrees.intleftSum=sum(root->left);intrightSum=sum(root->right);// Check the Sum Tree property for the current node and// recursively verify both subtrees.return(root->data==leftSum+rightSum)&&isSumTree(root->left)&&isSumTree(root->right);}intmain(){// Create the following binary tree://// 3// / \ // 1 2//Node*root=newNode(3);root->left=newNode(1);root->right=newNode(2);cout<<(isSumTree(root)?"true":"false");return0;}
C
#include<stdbool.h>#include<stdio.h>#include<stdlib.h>typedefstructNode{intdata;structNode*left;structNode*right;}Node;// Creates a new tree node.Node*createNode(intdata){Node*node=(Node*)malloc(sizeof(Node));node->data=data;node->left=node->right=NULL;returnnode;}// Returns the sum of all nodes in the subtree rooted at 'root'.intsum(Node*root){if(root==NULL)return0;returnroot->data+sum(root->left)+sum(root->right);}// Returns true if the binary tree rooted at 'root' is a Sum Tree.boolisSumTree(Node*root){// An empty tree and a leaf node are always Sum Trees.if(root==NULL||(root->left==NULL&&root->right==NULL))returntrue;// Calculate the sum of nodes in the left and right subtrees.intleftSum=sum(root->left);intrightSum=sum(root->right);// Check the Sum Tree property for the current node and// recursively verify both subtrees.return(root->data==leftSum+rightSum)&&isSumTree(root->left)&&isSumTree(root->right);}intmain(){// Create the following binary tree://// 3// / \ // 1 2//Node*root=createNode(3);root->left=createNode(1);root->right=createNode(2);printf("%s",isSumTree(root)?"true":"false");return0;}
Java
classNode{intdata;Nodeleft,right;Node(intdata){this.data=data;left=right=null;}}classGFG{// Returns the sum of all nodes in the subtree rooted at// 'root'.staticintsum(Noderoot){if(root==null)return0;returnroot.data+sum(root.left)+sum(root.right);}// Returns true if the binary tree rooted at 'root' is a// Sum Tree.staticbooleanisSumTree(Noderoot){// An empty tree and a leaf node are always Sum// Trees.if(root==null||(root.left==null&&root.right==null))returntrue;// Calculate the sum of nodes in the left and right// subtrees.intleftSum=sum(root.left);intrightSum=sum(root.right);// Check the Sum Tree property for the current node// and recursively verify both subtrees.return(root.data==leftSum+rightSum)&&isSumTree(root.left)&&isSumTree(root.right);}publicstaticvoidmain(String[]args){// Create the following binary tree://// 3// / \// 1 2//Noderoot=newNode(3);root.left=newNode(1);root.right=newNode(2);System.out.println(isSumTree(root));}}
Python
classNode:def__init__(self,data):self.data=dataself.left=Noneself.right=None# Returns the sum of all nodes in the subtree rooted at 'root'.defsumTree(root):ifrootisNone:return0returnroot.data+sumTree(root.left)+sumTree(root.right)# Returns True if the binary tree rooted at 'root' is a Sum Tree.defisSumTree(root):# An empty tree and a leaf node are always Sum Trees.ifrootisNoneor(root.leftisNoneandroot.rightisNone):returnTrue# Calculate the sum of nodes in the left and right subtrees.left_sum=sumTree(root.left)right_sum=sumTree(root.right)# Check the Sum Tree property for the current node and# recursively verify both subtrees.return(root.data==left_sum+right_sumandisSumTree(root.left)andisSumTree(root.right))# Driver Codeif__name__=="__main__":# Create the following binary tree:## 3# / \# 1 2#root=Node(3)root.left=Node(1)root.right=Node(2)print("true"ifisSumTree(root)else"false")
C#
usingSystem;classNode{publicintdata;publicNodeleft,right;publicNode(intdata){this.data=data;left=right=null;}}classGFG{// Returns the sum of all nodes in the subtree rooted at// 'root'.staticintSum(Noderoot){if(root==null)return0;returnroot.data+Sum(root.left)+Sum(root.right);}// Returns true if the binary tree rooted at 'root' is a// Sum Tree.staticboolisSumTree(Noderoot){// An empty tree and a leaf node are always Sum// Trees.if(root==null||(root.left==null&&root.right==null))returntrue;// Calculate the sum of nodes in the left and right// subtrees.intleftSum=Sum(root.left);intrightSum=Sum(root.right);// Check the Sum Tree property for the current node// and recursively verify both subtrees.return(root.data==leftSum+rightSum)&&isSumTree(root.left)&&isSumTree(root.right);}staticvoidMain(){// Create the following binary tree://// 3// / \// 1 2//Noderoot=newNode(3);root.left=newNode(1);root.right=newNode(2);Console.WriteLine(isSumTree(root)?"true":"false");}}
JavaScript
classNode{constructor(data){this.data=data;this.left=null;this.right=null;}}// Returns the sum of all nodes in the subtree rooted at// 'root'.functionsum(root){if(root===null)return0;returnroot.data+sum(root.left)+sum(root.right);}// Returns true if the binary tree rooted at 'root' is a Sum// Tree.functionisSumTree(root){// An empty tree and a leaf node are always Sum Trees.if(root===null||(root.left===null&&root.right===null))returntrue;// Calculate the sum of nodes in the left and right// subtrees.constleftSum=sum(root.left);constrightSum=sum(root.right);// Check the Sum Tree property for the current node and// recursively verify both subtrees.return(root.data===leftSum+rightSum)&&isSumTree(root.left)&&isSumTree(root.right);}// Driver Code// Create the following binary tree://// 3// / \// 1 2//constroot=newNode(3);root.left=newNode(1);root.right=newNode(2);console.log(isSumTree(root)?"true":"false");
Output
true
[Better Approach] Using Post Order traversal - O(n) Time and O(h) Space
Instead of recomputing the sum of every subtree multiple times, process the tree in postorder so that the left and right subtree sums are available before checking the current node. Each recursive call returns the subtree sum if it is a Sum Tree; otherwise, it immediately propagates failure, allowing the entire tree to be verified in a single traversal.
Traverse the tree in postorder (left subtree, right subtree, then current node).
If the current node is NULL, return 0; if it is a leaf node, return its value as the subtree sum.
Recursively compute the sums of the left and right subtrees.
If either recursive call returns -1, immediately return -1 to indicate that the subtree is not a Sum Tree.
If the current node's value equals the sum of the left and right subtree sums, return the total subtree sum.
Otherwise, return -1 to indicate that the current subtree is not a Sum Tree.
C++
#include<iostream>usingnamespacestd;classNode{public:intdata;Node*left,*right;Node(intx){data=x;left=right=nullptr;}};// Returns the sum of the subtree if it is a Sum Tree.// Otherwise, returns -1.intcheck(Node*root){// An empty tree has sum 0.if(root==nullptr)return0;// A leaf node is always a Sum Tree.// Return its value as the subtree sum.if(root->left==nullptr&&root->right==nullptr)returnroot->data;// Calculate the sum of the left subtree.intleftSum=check(root->left);// If the left subtree is not a Sum Tree,// propagate the failure.if(leftSum==-1)return-1;// Calculate the sum of the right subtree.intrightSum=check(root->right);// If the right subtree is not a Sum Tree,// propagate the failure.if(rightSum==-1)return-1;// Check whether the current node satisfies// the Sum Tree property.if(root->data!=leftSum+rightSum)return-1;// Return the total sum of the current subtree.returnleftSum+rightSum+root->data;}// Returns true if the binary tree is a Sum Tree.boolisSumTree(Node*root){returncheck(root)!=-1;}intmain(){// Create the following binary tree://// 3// / \ // 1 2//Node*root=newNode(3);root->left=newNode(1);root->right=newNode(2);cout<<(isSumTree(root)?"true":"false");return0;}
C
#include<stdbool.h>#include<stdio.h>#include<stdlib.h>typedefstructNode{intdata;structNode*left;structNode*right;}Node;// Creates a new tree node.Node*createNode(intdata){Node*node=(Node*)malloc(sizeof(Node));node->data=data;node->left=node->right=NULL;returnnode;}// Returns the sum of the subtree if it is a Sum Tree.// Otherwise, returns -1.intcheck(Node*root){// An empty tree has sum 0.if(root==NULL)return0;// A leaf node is always a Sum Tree.// Return its value as the subtree sum.if(root->left==NULL&&root->right==NULL)returnroot->data;// Calculate the sum of the left subtree.intleftSum=check(root->left);// If the left subtree is not a Sum Tree,// propagate the failure.if(leftSum==-1)return-1;// Calculate the sum of the right subtree.intrightSum=check(root->right);// If the right subtree is not a Sum Tree,// propagate the failure.if(rightSum==-1)return-1;// Check whether the current node satisfies// the Sum Tree property.if(root->data!=leftSum+rightSum)return-1;// Return the total sum of the current subtree.returnleftSum+rightSum+root->data;}// Returns true if the binary tree is a Sum Tree.boolisSumTree(Node*root){returncheck(root)!=-1;}intmain(){// Create the following binary tree://// 3// / \ // 1 2//Node*root=createNode(3);root->left=createNode(1);root->right=createNode(2);printf("%s",isSumTree(root)?"true":"false");return0;}
Java
classNode{intdata;Nodeleft,right;Node(intdata){this.data=data;left=right=null;}}classGFG{// Returns the sum of the subtree if it is a Sum Tree.// Otherwise, returns -1.staticintcheck(Noderoot){// An empty tree has sum 0.if(root==null)return0;// A leaf node is always a Sum Tree.// Return its value as the subtree sum.if(root.left==null&&root.right==null)returnroot.data;// Calculate the sum of the left subtree.intleftSum=check(root.left);// If the left subtree is not a Sum Tree,// propagate the failure.if(leftSum==-1)return-1;// Calculate the sum of the right subtree.intrightSum=check(root.right);// If the right subtree is not a Sum Tree,// propagate the failure.if(rightSum==-1)return-1;// Check whether the current node satisfies// the Sum Tree property.if(root.data!=leftSum+rightSum)return-1;// Return the total sum of the current subtree.returnleftSum+rightSum+root.data;}// Returns true if the binary tree is a Sum Tree.staticbooleanisSumTree(Noderoot){returncheck(root)!=-1;}publicstaticvoidmain(String[]args){// Create the following binary tree://// 3// / \// 1 2//Noderoot=newNode(3);root.left=newNode(1);root.right=newNode(2);System.out.println(isSumTree(root));}}
Python
classNode:def__init__(self,data):self.data=dataself.left=Noneself.right=None# Returns the sum of the subtree if it is a Sum Tree.# Otherwise, returns -1.defcheck(root):# An empty tree has sum 0.ifrootisNone:return0# A leaf node is always a Sum Tree.# Return its value as the subtree sum.ifroot.leftisNoneandroot.rightisNone:returnroot.data# Calculate the sum of the left subtree.left_sum=check(root.left)# If the left subtree is not a Sum Tree,# propagate the failure.ifleft_sum==-1:return-1# Calculate the sum of the right subtree.right_sum=check(root.right)# If the right subtree is not a Sum Tree,# propagate the failure.ifright_sum==-1:return-1# Check whether the current node satisfies# the Sum Tree property.ifroot.data!=left_sum+right_sum:return-1# Return the total sum of the current subtree.returnleft_sum+right_sum+root.data# Returns True if the binary tree is a Sum Tree.defisSumTree(root):returncheck(root)!=-1# Driver Codeif__name__=="__main__":# Create the following binary tree:## 3# / \# 1 2#root=Node(3)root.left=Node(1)root.right=Node(2)print("true"ifisSumTree(root)else"false")
C#
usingSystem;classNode{publicintdata;publicNodeleft,right;publicNode(intdata){this.data=data;left=right=null;}}classGFG{// Returns the sum of the subtree if it is a Sum Tree.// Otherwise, returns -1.staticintCheck(Noderoot){// An empty tree has sum 0.if(root==null)return0;// A leaf node is always a Sum Tree.// Return its value as the subtree sum.if(root.left==null&&root.right==null)returnroot.data;// Calculate the sum of the left subtree.intleftSum=Check(root.left);// If the left subtree is not a Sum Tree,// propagate the failure.if(leftSum==-1)return-1;// Calculate the sum of the right subtree.intrightSum=Check(root.right);// If the right subtree is not a Sum Tree,// propagate the failure.if(rightSum==-1)return-1;// Check whether the current node satisfies// the Sum Tree property.if(root.data!=leftSum+rightSum)return-1;// Return the total sum of the current subtree.returnleftSum+rightSum+root.data;}// Returns true if the binary tree is a Sum Tree.staticboolisSumTree(Noderoot){returnCheck(root)!=-1;}staticvoidMain(){// Create the following binary tree://// 3// / \// 1 2//Noderoot=newNode(3);root.left=newNode(1);root.right=newNode(2);Console.WriteLine(isSumTree(root)?"true":"false");}}
JavaScript
classNode{constructor(data){this.data=data;this.left=null;this.right=null;}}// Returns the sum of the subtree if it is a Sum Tree.// Otherwise, returns -1.functioncheck(root){// An empty tree has sum 0.if(root===null)return0;// A leaf node is always a Sum Tree.// Return its value as the subtree sum.if(root.left===null&&root.right===null)returnroot.data;// Calculate the sum of the left subtree.constleftSum=check(root.left);// If the left subtree is not a Sum Tree,// propagate the failure.if(leftSum===-1)return-1;// Calculate the sum of the right subtree.constrightSum=check(root.right);// If the right subtree is not a Sum Tree,// propagate the failure.if(rightSum===-1)return-1;// Check whether the current node satisfies// the Sum Tree property.if(root.data!==leftSum+rightSum)return-1;// Return the total sum of the current subtree.returnleftSum+rightSum+root.data;}// Returns true if the binary tree is a Sum Tree.functionisSumTree(root){returncheck(root)!==-1;}// Driver Code// Create the following binary tree://// 3// / \// 1 2//constroot=newNode(3);root.left=newNode(1);root.right=newNode(2);console.log(isSumTree(root)?"true":"false");
Output
true
[Expected Approach] Using Sum Tree Property - O(n) Time and O(h) Space
A key property of a Sum Tree is that for every non-leaf Sum Tree node, the sum of all nodes in its subtree is equal to 2 × node->data. By first verifying that the left and right subtrees are Sum Trees, we can compute their sums in O(1) using this property instead of traversing the subtrees again.
If the current node is NULL or a leaf node, return true.
Recursively check whether the left and right subtrees are Sum Trees.
If either subtree is not a Sum Tree, return false.
Compute the left and right subtree sums in O(1) using the Sum Tree property (0 for NULL, node value for a leaf, otherwise 2 × child->data).
Check whether the current node's value equals the sum of the left and right subtree sums.
Return true if the condition holds; otherwise, return false.
C++
#include<iostream>usingnamespacestd;classNode{public:intdata;Node*left,*right;Node(intx){data=x;left=right=nullptr;}};// Returns true if the given node is a leaf node.boolisLeaf(Node*node){returnnode!=nullptr&&node->left==nullptr&&node->right==nullptr;}// Returns true if the binary tree rooted at 'root' is a Sum Tree.boolisSumTree(Node*root){intleftSum,rightSum;// An empty tree and a leaf node are always Sum Trees.if(root==nullptr||isLeaf(root))returntrue;// First, verify that both left and right subtrees are Sum Trees.if(isSumTree(root->left)&&isSumTree(root->right)){// Calculate the sum of the left subtree in O(1).if(root->left==nullptr)leftSum=0;elseif(isLeaf(root->left))leftSum=root->left->data;elseleftSum=2*root->left->data;// Calculate the sum of the right subtree in O(1).if(root->right==nullptr)rightSum=0;elseif(isLeaf(root->right))rightSum=root->right->data;elserightSum=2*root->right->data;// Check whether the current node satisfies// the Sum Tree property.returnroot->data==leftSum+rightSum;}// If either subtree is not a Sum Tree,// then the current tree cannot be a Sum Tree.returnfalse;}intmain(){// Create the following binary tree://// 3// / \ // 1 2//Node*root=newNode(3);root->left=newNode(1);root->right=newNode(2);cout<<(isSumTree(root)?"true":"false");return0;}
C
#include<stdbool.h>#include<stdio.h>#include<stdlib.h>typedefstructNode{intdata;structNode*left;structNode*right;}Node;// Creates a new tree node.Node*createNode(intdata){Node*node=(Node*)malloc(sizeof(Node));node->data=data;node->left=node->right=NULL;returnnode;}// Returns true if the given node is a leaf node.boolisLeaf(Node*node){returnnode!=NULL&&node->left==NULL&&node->right==NULL;}// Returns true if the binary tree rooted at 'root' is a Sum Tree.boolisSumTree(Node*root){intleftSum,rightSum;// An empty tree and a leaf node are always Sum Trees.if(root==NULL||isLeaf(root))returntrue;// First, verify that both left and right subtrees are Sum Trees.if(isSumTree(root->left)&&isSumTree(root->right)){// Calculate the sum of the left subtree in O(1).if(root->left==NULL)leftSum=0;elseif(isLeaf(root->left))leftSum=root->left->data;elseleftSum=2*root->left->data;// Calculate the sum of the right subtree in O(1).if(root->right==NULL)rightSum=0;elseif(isLeaf(root->right))rightSum=root->right->data;elserightSum=2*root->right->data;// Check whether the current node satisfies// the Sum Tree property.returnroot->data==leftSum+rightSum;}// If either subtree is not a Sum Tree,// then the current tree cannot be a Sum Tree.returnfalse;}intmain(){// Create the following binary tree://// 3// / \ // 1 2//Node*root=createNode(3);root->left=createNode(1);root->right=createNode(2);printf("%s",isSumTree(root)?"true":"false");return0;}
Java
classNode{intdata;Nodeleft,right;Node(intx){data=x;left=right=null;}}classGFG{// Returns true if the given node is a leaf node.staticbooleanisLeaf(Nodenode){returnnode!=null&&node.left==null&&node.right==null;}// Returns true if the binary tree rooted at 'root' is a// Sum Tree.staticbooleanisSumTree(Noderoot){intleftSum,rightSum;// An empty tree and a leaf node are always Sum// Trees.if(root==null||isLeaf(root))returntrue;// First, verify that both left and right subtrees// are Sum Trees.if(isSumTree(root.left)&&isSumTree(root.right)){// Calculate the sum of the left subtree in// O(1).if(root.left==null)leftSum=0;elseif(isLeaf(root.left))leftSum=root.left.data;elseleftSum=2*root.left.data;// Calculate the sum of the right subtree in// O(1).if(root.right==null)rightSum=0;elseif(isLeaf(root.right))rightSum=root.right.data;elserightSum=2*root.right.data;// Check whether the current node satisfies// the Sum Tree property.returnroot.data==leftSum+rightSum;}// If either subtree is not a Sum Tree,// then the current tree cannot be a Sum Tree.returnfalse;}publicstaticvoidmain(String[]args){// Create the following binary tree://// 3// / \// 1 2//Noderoot=newNode(3);root.left=newNode(1);root.right=newNode(2);System.out.println(isSumTree(root));}}
Python
classNode:def__init__(self,data):self.data=dataself.left=Noneself.right=None# Returns True if the given node is a leaf node.defis_leaf(node):returnnodeisnotNoneandnode.leftisNoneandnode.rightisNone# Returns True if the binary tree rooted at 'root' is a Sum Tree.defisSumTree(root):# An empty tree and a leaf node are always Sum Trees.ifrootisNoneoris_leaf(root):returnTrue# First, verify that both left and right subtrees are Sum Trees.ifisSumTree(root.left)andisSumTree(root.right):# Calculate the sum of the left subtree in O(1).ifroot.leftisNone:left_sum=0elifis_leaf(root.left):left_sum=root.left.dataelse:left_sum=2*root.left.data# Calculate the sum of the right subtree in O(1).ifroot.rightisNone:right_sum=0elifis_leaf(root.right):right_sum=root.right.dataelse:right_sum=2*root.right.data# Check whether the current node satisfies# the Sum Tree property.returnroot.data==left_sum+right_sum# If either subtree is not a Sum Tree,# then the current tree cannot be a Sum Tree.returnFalseif__name__=="__main__":# Create the following binary tree:## 3# / \# 1 2#root=Node(3)root.left=Node(1)root.right=Node(2)print("true"ifisSumTree(root)else"false")
C#
usingSystem;classNode{publicintdata;publicNodeleft,right;publicNode(intx){data=x;left=right=null;}}classGFG{// Returns true if the given node is a leaf node.staticboolIsLeaf(Nodenode){returnnode!=null&&node.left==null&&node.right==null;}// Returns true if the binary tree rooted at 'root' is a// Sum Tree.staticboolisSumTree(Noderoot){intleftSum,rightSum;// An empty tree and a leaf node are always Sum// Trees.if(root==null||IsLeaf(root))returntrue;// First, verify that both left and right subtrees// are Sum Trees.if(isSumTree(root.left)&&isSumTree(root.right)){// Calculate the sum of the left subtree in// O(1).if(root.left==null)leftSum=0;elseif(IsLeaf(root.left))leftSum=root.left.data;elseleftSum=2*root.left.data;// Calculate the sum of the right subtree in// O(1).if(root.right==null)rightSum=0;elseif(IsLeaf(root.right))rightSum=root.right.data;elserightSum=2*root.right.data;// Check whether the current node satisfies// the Sum Tree property.returnroot.data==leftSum+rightSum;}// If either subtree is not a Sum Tree,// then the current tree cannot be a Sum Tree.returnfalse;}staticvoidMain(){// Create the following binary tree://// 3// / \// 1 2//Noderoot=newNode(3);root.left=newNode(1);root.right=newNode(2);Console.WriteLine(isSumTree(root)?"true":"false");}}
JavaScript
classNode{constructor(data){this.data=data;this.left=null;this.right=null;}}// Returns true if the given node is a leaf node.functionisLeaf(node){returnnode!==null&&node.left===null&&node.right===null;}// Returns true if the binary tree rooted at 'root' is a Sum// Tree.functionisSumTree(root){letleftSum,rightSum;// An empty tree and a leaf node are always Sum Trees.if(root===null||isLeaf(root))returntrue;// First, verify that both left and right subtrees are// Sum Trees.if(isSumTree(root.left)&&isSumTree(root.right)){// Calculate the sum of the left subtree in O(1).if(root.left===null)leftSum=0;elseif(isLeaf(root.left))leftSum=root.left.data;elseleftSum=2*root.left.data;// Calculate the sum of the right subtree in O(1).if(root.right===null)rightSum=0;elseif(isLeaf(root.right))rightSum=root.right.data;elserightSum=2*root.right.data;// Check whether the current node satisfies// the Sum Tree property.returnroot.data===leftSum+rightSum;}// If either subtree is not a Sum Tree,// then the current tree cannot be a Sum Tree.returnfalse;}// Driver Code// Create the following binary tree://// 3// / \// 1 2//constroot=newNode(3);root.left=newNode(1);root.right=newNode(2);console.log(isSumTree(root)?"true":"false");