Given a binary tree, the task is to check for every node, its value is equal to the sum of values of its immediate left and right child. For NULL values, consider the value to be 0. Also, leaves are considered to follow the property.
[Expected Approach] Using Recursion - O(n) Time and O(h) Space:
The idea is traverse the binary tree recursively and check if the root node and its children satisfy the children sum property, which states that a node's value should equal the sum of its left and right children's values. The function checks if the current node's value matches this sum and recursively checks for both the subtrees.
Below is the implementation of this approach:
Output
1
Time Complexity: O(n), where n is the number of nodes in the tree. Auxiliary Space: O(h), where h is the height of the tree.
[Alternate Approach] Using Queue - O(n) Time and O(n) Space:
The idea is to traverse the tree using level order approach. For each node, check if it satisfies children sum property. If it does, then push its children nodes into the queue. Otherwise return 0.
Below is the implementation of this approach:
Output
1
Time Complexity: O(n), where n is the number of nodes in the tree. Auxiliary Space: O(n)