Given the root of a binary tree, determine if the binary tree holds children-sum property. For a tree to satisfy the children-sum property, each node’s value should be equal to the sum of values at its left and right node. The value of an empty node is considered as 0.

For example, the following binary tree holds the children-sum property:

Children Sum Property

Practice this problem

The idea is to traverse the binary tree in a postorder fashion. For each non-leaf node, check if the node’s value is equal to the sum of values at its left and right subtree. If this relation does not hold for any node, then the binary tree does not hold children-sum property.

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

C++


Download  Run Code

Output:

Binary tree holds children-sum property

Java


Download  Run Code

Output:

Binary tree holds children-sum property

Python


Download  Run Code

Output:

Binary tree holds children-sum property

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

 
Also See:

Fix children-sum property in a binary tree