Program to find most frequent subtree sum of a binary tree in Python

Suppose we have a binary tree, we have to find the most frequent subtree sum. The subtree sum of a node is the sum of all values under a node, including the node itself.

So, if the input is like

-6 3 6 Subtree sums: 3, 6, 3 (-6+3+6)

then the output will be 3 as it occurs twice ? once as the left leaf, and once as the sum of -6 + 3 + 6.

Algorithm

To solve this, we will follow these steps ?

  • count := an empty map to store frequency of each subtree sum
  • Define a function getSum() that takes a node
  • if node is null, then
    • return 0
  • mySum := getSum(left of node) + getSum(right of node) + value of node
  • count[mySum] := count[mySum] + 1
  • return mySum
  • From the main method, call getSum(root) and return the most frequent sum

Example

Let us see the following implementation to get better understanding ?

from collections import defaultdict

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

class Solution:
    def solve(self, root):
        count = defaultdict(int)
        
        def getSum(node):
            if not node:
                return 0
            
            mySum = getSum(node.left) + getSum(node.right) + node.val
            count[mySum] += 1
            return mySum
        
        getSum(root)
        return max(count, key=count.get)

# Test the solution
ob = Solution()
root = TreeNode(-6)
root.left = TreeNode(3)
root.right = TreeNode(6)

print("Most frequent subtree sum:", ob.solve(root))
Most frequent subtree sum: 3

How It Works

The algorithm performs a post-order traversal of the tree:

  1. For each node, calculate subtree sum by adding left subtree sum + right subtree sum + current node value
  2. Store the frequency of each subtree sum in a dictionary
  3. Return the sum with maximum frequency

For the example tree: left subtree sum = 3, right subtree sum = 6, root subtree sum = 3 + 6 + (-6) = 3. Since sum "3" appears twice, it's the most frequent.

Conclusion

This solution uses post-order traversal to calculate subtree sums and tracks their frequencies. The time complexity is O(n) where n is the number of nodes, making it efficient for finding the most frequent subtree sum.

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

260 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements