# 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,

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 –

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.

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

Subscribe
Notify of
Guest
Aivi

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

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.

Guest