Transform to Sum Tree
Given a Binary Tree of size N , where each node can have positive or negative values. Convert this to a tree where each node contains the sum of the left and right sub trees of the original tree. The values of leaf nodes are changed to 0.
Approach:
The problem can be solved recursively with post-order traversal (left-right-root), as we need the values of child nodes before updating the current node.
Steps:
领英推荐
int solve(Node* node){
if(node == NULL) return 0;
int left = solve(node->left);
int right = solve(node->right);
int originalValue = node->data;
node->data = left+right;
return originalValue + node->data;
}
void toSumTree(Node *node)
{
solve(node);
}
Time Complexity: O(N)
Space Complexity: O(N)
where N is number of nodes
Student || 3??Codechef (Max rating -1629) || 5?? C++/Problem Solving Hackerrank ||Codeforces Max Rating -1166|| CP Enthusiast || Problem Solver & Daily Streak Gold??Codechef || 300+Codechef || 200+ Codeforces
3 个月Interesting??