Given a binary tree, the task is to check if it is a Sum Tree. A Sum Tree is a Binary Tree where the value of a node is equal to the sum of the nodes present in its left subtree and right subtree. An empty tree is Sum Tree and the sum of an empty tree can be considered as 0. A leaf node is also considered a Sum Tree.
Example:
Input:
Output: True Explanation: The above tree follows the property of Sum Tree.
Input:
Output: False Explanation: The above tree doesn't follows the property of Sum Tree as 6 + 2 != 10.
[Naive Approach] By Checking Every Node - O(n^2) Time and O(h) Space:
The idea is to get the sum in 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.
Below is the implementation of the above approach:
C++
// C++ program to check if Binary tree// is sum tree or not#include<iostream>usingnamespacestd;classNode{public:intdata;Node*left;Node*right;Node(intx){data=x;left=right=nullptr;}};// A utility function to get the sum// of values in treeintsum(Node*root){if(root==NULL)return0;returnsum(root->left)+root->data+sum(root->right);}// Returns 1 if sum property holds for// the given node and both of its children boolisSumTree(Node*root){intls,rs;// If root is NULL or it's a leaf// node then return true if(root==nullptr||(root->left==nullptr&&root->right==nullptr))returntrue;// Get sum of nodes in left and// right subtrees ls=sum(root->left);rs=sum(root->right);// If the root and both of its // children satisfy the property // return true else falseif((root->data==ls+rs)&&isSumTree(root->left)&&isSumTree(root->right))returntrue;returnfalse;}intmain(){// create hard coded tree// 26// / \ // 10 3// / \ \ // 4 6 3Node*root=newNode(26);root->left=newNode(10);root->right=newNode(3);root->left->left=newNode(4);root->left->right=newNode(6);root->right->right=newNode(3);if(isSumTree(root))cout<<"True";elsecout<<"False";return0;}
C
// C program to check if Binary tree// is sum tree or not#include<stdio.h>#include<stdlib.h>structNode{intdata;structNode*left;structNode*right;};// A utility function to get the sum of values in treeintsum(structNode*root){if(root==NULL)return0;returnsum(root->left)+root->data+sum(root->right);}// Returns 1 if sum property holds for the // given node and both of its children intisSumTree(structNode*root){intls,rs;// If root is NULL or it's a leaf node // then return true if(root==NULL||(root->left==NULL&&root->right==NULL))return1;// Get sum of nodes in left and right subtrees ls=sum(root->left);rs=sum(root->right);// If the root and both of its children satisfy // the property, return true else falseif((root->data==ls+rs)&&isSumTree(root->left)&&isSumTree(root->right))return1;return0;}structNode*createNode(intx){structNode*node=(structNode*)malloc(sizeof(structNode));node->data=x;node->left=node->right=NULL;returnnode;}intmain(){// create hard coded tree// 26// / \ // 10 3// / \ \ // 4 6 3structNode*root=createNode(26);root->left=createNode(10);root->right=createNode(3);root->left->left=createNode(4);root->left->right=createNode(6);root->right->right=createNode(3);if(isSumTree(root))printf("True");elseprintf("False");return0;}
Java
// Java program to check if Binary tree// is sum tree or notclassNode{intdata;Nodeleft,right;Node(intx){data=x;left=right=null;}}// A utility function to get the sum of values in treeclassGfG{staticintsum(Noderoot){if(root==null)return0;returnsum(root.left)+root.data+sum(root.right);}// Returns true if sum property holds for the // given node and both of its children staticbooleanisSumTree(Noderoot){intls,rs;// If root is null or it's a leaf node // then return true if(root==null||(root.left==null&&root.right==null))returntrue;// Get sum of nodes in left and right subtrees ls=sum(root.left);rs=sum(root.right);// If the root and both of its children satisfy // the property, return true else falsereturn(root.data==ls+rs)&&isSumTree(root.left)&&isSumTree(root.right);}publicstaticvoidmain(String[]args){// create hard coded tree// 26// / \// 10 3// / \ \// 4 6 3Noderoot=newNode(26);root.left=newNode(10);root.right=newNode(3);root.left.left=newNode(4);root.left.right=newNode(6);root.right.right=newNode(3);if(isSumTree(root))System.out.println("True");elseSystem.out.println("False");}}
Python
# Python3 program to implement # the above approachclassNode:def__init__(self,x):self.data=xself.left=Noneself.right=None# A utility function to get the sum of values in treedefsum_tree(root):ifrootisNone:return0returnsum_tree(root.left)+root.data+sum_tree(root.right)# Returns True if sum property holds for the given # node and both of its children defis_sum_tree(root):# If root is None or it's a leaf node then return True ifrootisNoneor(root.leftisNoneandroot.rightisNone):returnTrue# Get sum of nodes in left and right subtrees ls=sum_tree(root.left)rs=sum_tree(root.right)# If the root and both of its children # satisfy the property, return True else Falsereturnroot.data==ls+rsand \
is_sum_tree(root.left)and \
is_sum_tree(root.right)if__name__=="__main__":# create hard coded tree# 26# / \# 10 3# / \ \# 4 6 3root=Node(26)root.left=Node(10)root.right=Node(3)root.left.left=Node(4)root.left.right=Node(6)root.right.right=Node(3)ifis_sum_tree(root):print("True")else:print("False")
C#
// C# program to check if Binary tree// is sum tree or notusingSystem;classNode{publicintdata;publicNodeleft,right;publicNode(intx){data=x;left=right=null;}}classGfG{// A utility function to get the sum of values in treestaticintSum(Noderoot){if(root==null)return0;returnSum(root.left)+root.data+Sum(root.right);}// Returns true if sum property holds for // the given node and both of its children staticboolIsSumTree(Noderoot){intls,rs;// If root is null or it's a leaf node then return true if(root==null||(root.left==null&&root.right==null))returntrue;// Get sum of nodes in left and right subtrees ls=Sum(root.left);rs=Sum(root.right);// If the root and both of its children // satisfy the property, return true else falsereturn(root.data==ls+rs)&&IsSumTree(root.left)&&IsSumTree(root.right);}staticvoidMain(string[]args){// create hard coded tree// 26// / \// 10 3// / \ \// 4 6 3Noderoot=newNode(26);root.left=newNode(10);root.right=newNode(3);root.left.left=newNode(4);root.left.right=newNode(6);root.right.right=newNode(3);if(IsSumTree(root))Console.WriteLine("True");elseConsole.WriteLine("False");}}
JavaScript
// JavaScript program to check if Binary tree// is sum tree or notclassNode{constructor(x){this.data=x;this.left=this.right=null;}}// A utility function to get the sum of values in treefunctionsum(root){if(root==null)return0;returnsum(root.left)+root.data+sum(root.right);}// Returns true if sum property holds for the given// node and both of its children functionisSumTree(root){// If root is null or it's a leaf node then return true if(root==null||(root.left==null&&root.right==null))returntrue;// Get sum of nodes in left and right subtrees letls=sum(root.left);letrs=sum(root.right);// If the root and both of its children satisfy the// property, return true else falsereturnroot.data==ls+rs&&isSumTree(root.left)&&isSumTree(root.right);}// create hard coded tree// 26// / \// 10 3// / \ \// 4 6 3letroot=newNode(26);root.left=newNode(10);root.right=newNode(3);root.left.left=newNode(4);root.left.right=newNode(6);root.right.right=newNode(3);if(isSumTree(root)){console.log("True");}else{console.log("False");}
Output
True
Time Complexity: O(n^2), where n are the number of nodes in binary tree. Auxiliary Space: O(h)
[Expected Approach] Calculating left and right subtree sum directly - O(n) Time and O(h) Space:
The idea is to first check if left and right subtrees are sum trees. If they are, then the sum of left and right subtrees can easily be obtained in O(1) time.
Step by Step implementation:
For a given root node, recursively check if left subtree and right subtree are sum trees. If one of them or both are not sum tree, simply return false.
If both of them are sum trees, then we can find the sum of left subtree and right subtree in O(1) using the following conditions:
If the root is null, then the sum is 0.
If the root is a leaf node, then sum is equal to root's value.
Otherwise, the sum if equal to twice of root's value. This is because this subtree is a sum tree. So the sum of this subtree's subtree is equal to root's value. So the total sum becomes 2*root->val.
Below is the implementation of the above approach:
C++
// C++ program to check if Binary tree// is sum tree or not#include<bits/stdc++.h>usingnamespacestd;classNode{public:intdata;Node*left;Node*right;Node(intx){data=x;left=right=nullptr;}};// Utility function to check if // the given node is leaf or notboolisLeaf(Node*node){if(node==nullptr)returnfalse;if(node->left==nullptr&&node->right==nullptr)returntrue;returnfalse;}boolisSumTree(Node*root){intls,rs;// If node is NULL or it's a leaf node then// return trueif(root==nullptr||isLeaf(root))returntrue;// If the left subtree and right subtree are sum trees,// then we can find subtree sum in O(1).if(isSumTree(root->left)&&isSumTree(root->right)){// Get the sum of nodes in left subtreeif(root->left==nullptr)ls=0;elseif(isLeaf(root->left))ls=root->left->data;elsels=2*(root->left->data);// Get the sum of nodes in right subtreeif(root->right==nullptr)rs=0;elseif(isLeaf(root->right))rs=root->right->data;elsers=2*(root->right->data);// If root's data is equal to sum of nodes in left// and right subtrees then return true else return falsereturn(root->data==ls+rs);}// if either of left or right subtree is not // sum tree, then return false.returnfalse;}intmain(){// create hard coded tree// 26// / \ // 10 3// / \ \ // 4 6 3Node*root=newNode(26);root->left=newNode(10);root->right=newNode(3);root->left->left=newNode(4);root->left->right=newNode(6);root->right->right=newNode(3);if(isSumTree(root))cout<<"True";elsecout<<"False";return0;}
C
// C program to check if Binary tree// is sum tree or not#include<stdio.h>#include<stdlib.h>structNode{intdata;structNode*left;structNode*right;};// Utility function to check if the given node is leaf or notintisLeaf(structNode*node){if(node==NULL)return0;if(node->left==NULL&&node->right==NULL)return1;return0;}intisSumTree(structNode*root){intls,rs;// If node is NULL or it's a leaf node then return trueif(root==NULL||isLeaf(root))return1;// If the left subtree and right subtree are sum trees,// then we can find subtree sum in O(1).if(isSumTree(root->left)&&isSumTree(root->right)){// Get the sum of nodes in left subtreeif(root->left==NULL)ls=0;elseif(isLeaf(root->left))ls=root->left->data;elsels=2*(root->left->data);// Get the sum of nodes in right subtreeif(root->right==NULL)rs=0;elseif(isLeaf(root->right))rs=root->right->data;elsers=2*(root->right->data);// If root's data is equal to sum of nodes in left// and right subtrees then return true else return falsereturn(root->data==ls+rs);}// if either of left or right subtree // is not sum tree, then return false.return0;}structNode*createNode(intx){structNode*node=(structNode*)malloc(sizeof(structNode));node->data=x;node->left=node->right=NULL;returnnode;}intmain(){// create hard coded tree// 26// / \ // 10 3// / \ \ // 4 6 3structNode*root=createNode(26);root->left=createNode(10);root->right=createNode(3);root->left->left=createNode(4);root->left->right=createNode(6);root->right->right=createNode(3);if(isSumTree(root))printf("True");elseprintf("False");return0;}
Java
// Java program to check if Binary tree // is sum tree or notclassNode{intdata;Nodeleft,right;Node(intx){data=x;left=right=null;}}classGfG{// Utility function to check if the given node is leaf or notstaticbooleanisLeaf(Nodenode){if(node==null)returnfalse;if(node.left==null&&node.right==null)returntrue;returnfalse;}staticbooleanisSumTree(Noderoot){intls,rs;// If node is null or it's a leaf node then return trueif(root==null||isLeaf(root))returntrue;// If the left subtree and right subtree are sum trees,// then we can find subtree sum in O(1).if(isSumTree(root.left)&&isSumTree(root.right)){// Get the sum of nodes in left subtreeif(root.left==null)ls=0;elseif(isLeaf(root.left))ls=root.left.data;elsels=2*(root.left.data);// Get the sum of nodes in right subtreeif(root.right==null)rs=0;elseif(isLeaf(root.right))rs=root.right.data;elsers=2*(root.right.data);// If root's data is equal to sum of nodes in left// and right subtrees then return true else return falsereturnroot.data==ls+rs;}// if either of left or right subtree is not // sum tree, then return false.returnfalse;}publicstaticvoidmain(String[]args){// create hard coded tree// 26// / \// 10 3// / \ \// 4 6 3Noderoot=newNode(26);root.left=newNode(10);root.right=newNode(3);root.left.left=newNode(4);root.left.right=newNode(6);root.right.right=newNode(3);if(isSumTree(root))System.out.println("True");elseSystem.out.println("False");}}
Python
# Python3 program to check if# Binary tree is sum tree or notclassNode:def__init__(self,x):self.data=xself.left=Noneself.right=None# Utility function to check if the# given node is leaf or notdefis_leaf(node):ifnodeisNone:returnFalseifnode.leftisNoneandnode.rightisNone:returnTruereturnFalsedefis_sum_tree(root):# If node is None or it's a leaf node then return TrueifrootisNoneoris_leaf(root):returnTrue# If the left subtree and right subtree are sum trees,# then we can find subtree sum in O(1).ifis_sum_tree(root.left)andis_sum_tree(root.right):# Get the sum of nodes in left subtreeifroot.leftisNone:ls=0elifis_leaf(root.left):ls=root.left.dataelse:ls=2*root.left.data# Get the sum of nodes in right subtreeifroot.rightisNone:rs=0elifis_leaf(root.right):rs=root.right.dataelse:rs=2*root.right.data# If root's data is equal to sum of nodes in left# and right subtrees then return True else return Falsereturnroot.data==ls+rs# if either of left or right subtree is not sum# tree, then return False.returnFalseif__name__=="__main__":# create hard coded tree# 26# / \# 10 3# / \ \# 4 6 3root=Node(26)root.left=Node(10)root.right=Node(3)root.left.left=Node(4)root.left.right=Node(6)root.right.right=Node(3)ifis_sum_tree(root):print("True")else:print("False")
C#
// C# program to check if Binary tree// is sum tree or notusingSystem;classNode{publicintdata;publicNodeleft,right;publicNode(intx){data=x;left=right=null;}}classGfG{// Utility function to check if the given // node is leaf or notstaticboolIsLeaf(Nodenode){if(node==null)returnfalse;if(node.left==null&&node.right==null)returntrue;returnfalse;}staticboolIsSumTree(Noderoot){intls,rs;// If node is null or it's a leaf node // then return trueif(root==null||IsLeaf(root))returntrue;// If the left subtree and right subtree are sum trees,// then we can find subtree sum in O(1).if(IsSumTree(root.left)&&IsSumTree(root.right)){// Get the sum of nodes in left subtreeif(root.left==null)ls=0;elseif(IsLeaf(root.left))ls=root.left.data;elsels=2*root.left.data;// Get the sum of nodes in right subtreeif(root.right==null)rs=0;elseif(IsLeaf(root.right))rs=root.right.data;elsers=2*root.right.data;// If root's data is equal to sum of // nodes in left and right subtrees // then return true else return falsereturnroot.data==ls+rs;}// if either of left or right subtree is // not sum tree, then return false.returnfalse;}staticvoidMain(string[]args){// create hard coded tree// 26// / \// 10 3// / \ \// 4 6 3Noderoot=newNode(26);root.left=newNode(10);root.right=newNode(3);root.left.left=newNode(4);root.left.right=newNode(6);root.right.right=newNode(3);if(IsSumTree(root))Console.WriteLine("True");elseConsole.WriteLine("False");}}
JavaScript
classNode{constructor(x){this.data=x;this.left=null;this.right=null;}}// Utility function to check if the given// node is leaf or notfunctionisLeaf(node){if(node===null)returnfalse;if(node.left===null&&node.right===null)returntrue;returnfalse;}functionisSumTree(root){letls,rs;// If node is null or it's a leaf node then return trueif(root===null||isLeaf(root))returntrue;// If the left subtree and right subtree are sum trees,// then we can find subtree sum in O(1).if(isSumTree(root.left)&&isSumTree(root.right)){// Get the sum of nodes in left subtreeif(root.left===null)ls=0;elseif(isLeaf(root.left))ls=root.left.data;elsels=2*root.left.data;// Get the sum of nodes in right subtreeif(root.right===null)rs=0;elseif(isLeaf(root.right))rs=root.right.data;elsers=2*root.right.data;// If root's data is equal to sum of nodes in left// and right subtrees then return true else return falsereturnroot.data===ls+rs;}// if either of left or right subtree is not // sum tree, then return false.returnfalse;}// create hard coded tree// 26// / \// 10 3// / \ \// 4 6 3letroot=newNode(26);root.left=newNode(10);root.right=newNode(3);root.left.left=newNode(4);root.left.right=newNode(6);root.right.right=newNode(3);if(isSumTree(root))console.log("True");elseconsole.log("False");
Output
True
Time Complexity: O(n), where n are the number of nodes in binary tree. Auxiliary Space: O(h)
[Alternate Approach] Using post order traversal - O(n) Time and O(h) Space:
The idea is recursively check if the left and right subtrees are sum trees. If a subtree is sum tree, it will return the sum of its root node, left tree and right tree. Otherwise it will return -1.
Step by step implementation:
For each current node, recursively check the left and right subtree for sum tree.
If the subtree is sum tree, it will return the sum of its root node, left tree and right tree.
Compare the sum of left subtree and right subtree with the root node. If they are equal, return sum of root node, left subtree and right subtree. Otherwise return -1.
Below is the implementation of the above approach:
C++
// C++ program to check if Binary tree// is sum tree or not#include<bits/stdc++.h>usingnamespacestd;classNode{public:intdata;Node*left;Node*right;Node(intx){data=x;left=right=nullptr;}};// returns sum if tree is SumTree// else return -1intisSumTree(Node*root){if(root==nullptr)return0;// If node is leaf node, return its value. if(root->left==nullptr&&root->right==nullptr)returnroot->data;// Calculate left subtree sumintls=isSumTree(root->left);// if left subtree is not sum tree,// return -1.if(ls==-1)return-1;// Calculate right subtree sumintrs=isSumTree(root->right);// if right subtree is not sum tree,// return -1.if(rs==-1)return-1;if(ls+rs==root->data)returnls+rs+root->data;elsereturn-1;}intmain(){// create hard coded tree// 26// / \ // 10 3// / \ \ // 4 6 3Node*root=newNode(26);root->left=newNode(10);root->right=newNode(3);root->left->left=newNode(4);root->left->right=newNode(6);root->right->right=newNode(3);if(isSumTree(root)!=-1)cout<<"True";elsecout<<"False";return0;}
C
// C program to check if Binary tree// is sum tree or not#include<stdio.h>#include<stdlib.h>structNode{intdata;structNode*left;structNode*right;};// returns sum if tree is SumTree// else return -1intisSumTree(structNode*root){if(root==NULL)return0;// If node is leaf node, return its value.if(root->left==NULL&&root->right==NULL)returnroot->data;// Calculate left subtree sumintls=isSumTree(root->left);// if left subtree is not sum tree, return -1.if(ls==-1)return-1;// Calculate right subtree sumintrs=isSumTree(root->right);// if right subtree is not sum tree, return -1.if(rs==-1)return-1;if(ls+rs==root->data)returnls+rs+root->data;elsereturn-1;}structNode*createNode(intx){structNode*node=(structNode*)malloc(sizeof(structNode));node->data=x;node->left=node->right=NULL;returnnode;}intmain(){// create hard coded tree// 26// / \ // 10 3// / \ \ // 4 6 3structNode*root=createNode(26);root->left=createNode(10);root->right=createNode(3);root->left->left=createNode(4);root->left->right=createNode(6);root->right->right=createNode(3);if(isSumTree(root)!=-1)printf("True");elseprintf("False");return0;}
Java
// Java program to check if Binary tree// is sum tree or notclassNode{intdata;Nodeleft,right;Node(intx){data=x;left=right=null;}}classGfG{// returns sum if tree is SumTree// else return -1staticintisSumTree(Noderoot){if(root==null)return0;// If node is leaf node, return its value.if(root.left==null&&root.right==null)returnroot.data;// Calculate left subtree sumintls=isSumTree(root.left);// if left subtree is not sum tree, return -1.if(ls==-1)return-1;// Calculate right subtree sumintrs=isSumTree(root.right);// if right subtree is not sum tree, return -1.if(rs==-1)return-1;if(ls+rs==root.data)returnls+rs+root.data;elsereturn-1;}publicstaticvoidmain(String[]args){// create hard coded tree// 26// / \// 10 3// / \ \// 4 6 3Noderoot=newNode(26);root.left=newNode(10);root.right=newNode(3);root.left.left=newNode(4);root.left.right=newNode(6);root.right.right=newNode(3);if(isSumTree(root)!=-1)System.out.println("True");elseSystem.out.println("False");}}
Python
# Python3 program to check if# Binary tree is sum tree or notclassNode:def__init__(self,x):self.data=xself.left=Noneself.right=None# returns sum if tree is SumTree# else return -1defis_sum_tree(root):ifrootisNone:return0# If node is leaf node, return its value.ifroot.leftisNoneandroot.rightisNone:returnroot.data# Calculate left subtree sumls=is_sum_tree(root.left)# if left subtree is not sum tree, return -1.ifls==-1:return-1# Calculate right subtree sumrs=is_sum_tree(root.right)# if right subtree is not sum tree, return -1.ifrs==-1:return-1ifls+rs==root.data:returnls+rs+root.dataelse:return-1if__name__=="__main__":# create hard coded tree# 26# / \# 10 3# / \ \# 4 6 3root=Node(26)root.left=Node(10)root.right=Node(3)root.left.left=Node(4)root.left.right=Node(6)root.right.right=Node(3)ifis_sum_tree(root)!=-1:print("True")else:print("False")
C#
// C# program to check if Binary tree// is sum tree or notusingSystem;classNode{publicintdata;publicNodeleft,right;publicNode(intx){data=x;left=right=null;}}classGfG{// returns sum if tree is SumTree// else return -1staticintIsSumTree(Noderoot){if(root==null)return0;// If node is leaf node, return its value.if(root.left==null&&root.right==null)returnroot.data;// Calculate left subtree sumintls=IsSumTree(root.left);// if left subtree is not sum tree, return -1.if(ls==-1)return-1;// Calculate right subtree sumintrs=IsSumTree(root.right);// if right subtree is not sum tree, return -1.if(rs==-1)return-1;if(ls+rs==root.data)returnls+rs+root.data;elsereturn-1;}staticvoidMain(string[]args){// create hard coded tree// 26// / \// 10 3// / \ \// 4 6 3Noderoot=newNode(26);root.left=newNode(10);root.right=newNode(3);root.left.left=newNode(4);root.left.right=newNode(6);root.right.right=newNode(3);if(IsSumTree(root)!=-1)Console.WriteLine("True");elseConsole.WriteLine("False");}}
JavaScript
// JavaScript program to check if// Binary tree is sum tree or notclassNode{constructor(x){this.data=x;this.left=null;this.right=null;}}// returns sum if tree is SumTree// else return -1functionisSumTree(root){if(root===null)return0;// If node is leaf node, return its value.if(root.left===null&&root.right===null)returnroot.data;// Calculate left subtree sumconstls=isSumTree(root.left);// if left subtree is not sum tree, return -1.if(ls===-1)return-1;// Calculate right subtree sumconstrs=isSumTree(root.right);// if right subtree is not sum tree, return -1.if(rs===-1)return-1;if(ls+rs===root.data)returnls+rs+root.data;elsereturn-1;}// create hard coded tree// 26// / \// 10 3// / \ \// 4 6 3letroot=newNode(26);root.left=newNode(10);root.right=newNode(3);root.left.left=newNode(4);root.left.right=newNode(6);root.right.right=newNode(3);if(isSumTree(root)!==-1)console.log("True");elseconsole.log("False");
Output
True
Time Complexity: O(n), where n are the number of nodes in binary tree. Auxiliary Space: O(h)