Check if given binary tree is a sum tree or not

Given a binary tree, check if it is a sum tree or not. In a sum tree, value at each non-leaf node is equal to the sum of all elements present in its left and right subtree. The value of a leaf node can be anything.

 

For example,

 
Sum Tree

 


 

We can easily solve this problem by using recursion. The idea is to traverse the tree in postorder fashion. Then for each non-leaf node, we check if node’s value is equal to sum of all elements present in its left subtree and right subtree. If this relation do not hold true for any node, then the given binary tree cannot be a sum tree.

 
C++ implementation –
 

Download   Run Complete Code

 
The time complexity of above solution is O(n) and need O(h) extra space for the call stack where h is the height of the tree.
 

Thanks for reading.
 

Please use ideone or C++ Shell or any other online compiler link to post code in comments.
Like us? Please spread the word and help us grow. Happy coding 🙂
 


Get great deals at Amazon




Leave a Reply

avatar
  Subscribe  
newest oldest most voted
Notify of
Aivi
Guest
Aivi

Why do we have to return 2*root->key at the end ? and not just return root->key??

arandomguy
Guest
arandomguy

Because root->key is equal to the sum of subtree rooted at root, so the sum of tree rooted at its parent is equal to twice of root->key, as sum is root->key + sum of tree rooted at root which is also root->key by the property of sum tree.

Nishad
Guest
Nishad

Why are we returning an int here? Is it not boolean as we are checking if it is a sum tree or not?

Also, why are we returning 2*root->key?

arandomguy
Guest
arandomguy

INT_MIN here is working as a flag here instead.