Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
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
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:
- For each node, calculate subtree sum by adding left subtree sum + right subtree sum + current node value
- Store the frequency of each subtree sum in a dictionary
- 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.
