Program to find a tree by updating values with left and right subtree sum with itself in Python

A binary tree can be transformed by updating each node's value to include the sum of all values in its left and right subtrees. This creates a new tree where each node contains its original value plus the total sum of all descendant nodes.

Original Tree 2 3 4 9 7 Transform Updated Tree 25 19 4 9 7

Algorithm Steps

The transformation follows a post-order traversal approach ?

  • Define a recursive function tree_sum() that takes a tree node

  • If the node is null, return 0

  • Recursively calculate sums for left and right subtrees

  • Update current node's value = original value + left subtree sum + right subtree sum

  • Return the updated node value

Implementation

class TreeNode:
    def __init__(self, data, left=None, right=None):
        self.data = data
        self.left = left
        self.right = right

def inorder(root):
    if root:
        inorder(root.left)
        print(root.data, end=', ')
        inorder(root.right)

class Solution:
    def solve(self, root):
        def tree_sum(root):
            if root is None:
                return 0
            
            left_sum = tree_sum(root.left)
            right_sum = tree_sum(root.right)
            root.data = root.data + left_sum + right_sum
            return root.data
        
        tree_sum(root)
        return root

# Create the binary tree
ob = Solution()
root = TreeNode(2)
root.left = TreeNode(3)
root.right = TreeNode(4)
root.left.left = TreeNode(9)
root.left.right = TreeNode(7)

# Transform the tree
print("Original tree (inorder):")
inorder(root)
print("\n")

ob.solve(root)

print("Updated tree (inorder):")
inorder(root)
Original tree (inorder):
9, 3, 7, 2, 4, 

Updated tree (inorder):
9, 19, 7, 25, 4, 

How It Works

For each node, the algorithm calculates ?

  • Leaf nodes: Keep their original values (9, 7, 4)

  • Node 3: 3 + 9 + 7 = 19 (original + left child + right child)

  • Root node 2: 2 + 19 + 4 = 25 (original + left subtree sum + right subtree sum)

Time and Space Complexity

  • Time Complexity: O(n) where n is the number of nodes

  • Space Complexity: O(h) where h is the height of the tree due to recursion stack

Conclusion

This algorithm efficiently transforms a binary tree by updating each node's value with the sum of its subtrees using post-order traversal. The transformation preserves the tree structure while creating meaningful aggregate values at each node.

Updated on: 2026-03-25T11:03:30+05:30

326 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements