Given a binary tree, the task is to check if it is a Sum Tree. A Sum Tree is a Binary Tree where the value of a node is equal to the sum of the nodes present in its left subtree and right subtree. An empty tree is Sum Tree and the sum of an empty tree can be considered as 0. A leaf node is also considered a Sum Tree.
[Naive Approach] By Checking Every Node - O(n^2) Time and O(h) Space:
The idea is to get the sum in the left subtree and right subtree for each node and compare it with the node's value. Also recursively check if the left and right subtree are sum trees.
Below is the implementation of the above approach:
Output
True
Time Complexity: O(n^2), where n are the number of nodes in binary tree. Auxiliary Space: O(h)
[Expected Approach] Calculating left and right subtree sum directly - O(n) Time and O(h) Space:
The idea is to first check if left and right subtrees are sum trees. If they are, then the sum of left and right subtrees can easily be obtained in O(1) time.
Step by Step implementation:
For a given root node, recursively check if left subtree and right subtree are sum trees. If one of them or both are not sum tree, simply return false.
If both of them are sum trees, then we can find the sum of left subtree and right subtree in O(1) using the following conditions:
If the root is null, then the sum is 0.
If the root is a leaf node, then sum is equal to root's value.
Otherwise, the sum if equal to twice of root's value. This is because this subtree is a sum tree. So the sum of this subtree's subtree is equal to root's value. So the total sum becomes 2*root->val.
Below is the implementation of the above approach:
Output
True
Time Complexity: O(n), where n are the number of nodes in binary tree. Auxiliary Space: O(h)
[Alternate Approach] Using post order traversal - O(n) Time and O(h) Space:
The idea is recursively check if the left and right subtrees are sum trees. If a subtree is sum tree, it will return the sum of its root node, left tree and right tree. Otherwise it will return -1.
Step by step implementation:
For each current node, recursively check the left and right subtree for sum tree.
If the subtree is sum tree, it will return the sum of its root node, left tree and right tree.
Compare the sum of left subtree and right subtree with the root node. If they are equal, return sum of root node, left subtree and right subtree. Otherwise return -1.
Below is the implementation of the above approach:
Output
True
Time Complexity: O(n), where n are the number of nodes in binary tree. Auxiliary Space: O(h)