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

For example, the following binary tree is a sum tree.

Sum Tree

Practice this problem

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

The algorithm can be implemented as follows in C++, Java, and Python:

C++


Download  Run Code

Output:

Binary tree is a sum tree

Java


Download  Run Code

Output:

Binary tree is a sum tree

Python


Download  Run Code

Output:

Binary tree is a sum tree

The time complexity of the above solution is O(n), where n is the total number of nodes in the binary tree. The program requires O(h) extra space for the call stack, where h is the height of the tree.