Sum Tree
Given a Binary Tree. Check for the Sum Tree for every node except the leaf node. Return true if it is a Sum Tree otherwise, return false.
A SumTree 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 also a Sum Tree as the sum of an empty tree can be considered to be 0. A leaf node is also considered a Sum Tree.
Approach:
The most efficient way to solve this problem is to use a recursive post-order traversal. This approach allows us to calculate subtree sums from the bottom up, making it easier to check the sum property for each non-leaf node. Here’s a step-by-step breakdown of the approach:
pair<bool,int>solve(Node* root){
if(root == NULL){
pair<bool,int>p = make_pair(true, 0);
return p;
}
if(root->left == NULL && root->right == NULL){
pair<bool,int>p = make_pair(true, root->data);
return p;
}
pair<bool,int>left = solve(root->left);
pair<bool,int>right = solve(root->right);
bool isSumTreeNot = (root->data == left.second + right.second);
bool check = left.first && right.first && isSumTreeNot;
int sum = root->data + left.second + right.second;
return make_pair(check, sum);
}
bool isSumTree(Node* root)
{
return solve(root).first;
}
领英推荐
Explanation :
Time Complexity : O(N)
Space Complexity : O(N)