![]() |
VOOZH | about |
Given a Binary Tree, convert it to a tree where each node contains the sum of the left and right sub trees in the original tree. The values of leaf nodes are changed to 0.
Input:
👁 2056957837Output:
👁 2056957921
Table of Content
First store the sum of each subtree in a HashMap using one traversal, then in a second traversal update each node using the stored values.
map<Node*, int> to store subtree sums 0 4 0 20 0 12 0
The idea is to use postorder traversal (Left → Right → Node) so that we first compute the sum of left and right subtrees before updating the current node. While doing this, we keep track of the original value to return the correct subtree sum upward.
0 4 0 20 0 12 0