This post is completed by 3 users

  • 1
Add to List
Medium

183. Convert binary tree to its Sum tree

Objective: Given a binary tree, write an algorithm to convert it into its Sum tree.

What is a Sum tree: A sum tree of a binary tree, is a tree where each node in the converted tree will contain the sum of the left and right sub-trees in the original tree.

Example:

Convert binary tree to its Sum tree.

Approach:

  1. Recursively calculate the left sum from the left sum tree.
  2. Recursively calculate the right sum from the right tree.
  3. prepare the return root.data + left sum + right sum.
  4. Update the root data as root.data = left sum + right sum.
  5. update the newRoot = root.
  6. See the code for a better understanding.
 

Output:

Original Tree: -2 -1 4 5 -6 3 10
Sum tree: 0 2 0 8 0 4 0