VOOZH about

URL: https://www.geeksforgeeks.org/dsa/convert-a-given-tree-to-sum-tree/

⇱ Transform to Sum Tree - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Transform to Sum Tree

Last Updated : 20 May, 2026

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:

👁 2056957837

Output:

👁 2056957921

Using Hash Map or Dictionary - O(n) Time and O(n) Space

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.

  • Create a map<Node*, int> to store subtree sums
  • First traversal: Compute sum of left + right + node and Store in map :
  • For each node: New value = (sum of left subtree + sum of right subtree)
  • Return updated tree.

Output
 0 4 0 20 0 12 0

[Alternative Approach] Using Postorder Traversal - O(n) Time and O(h) Space

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.

  • Traverse tree using postorder (left → right → root)
  • For each node, store old value, recursively get sum of left subtree, recursively get sum of right subtree and update node value = left sum + right sum
  • Return (new node value + old value) to parent

Output
 0 4 0 20 0 12 0
Comment
Article Tags: