- Trending Categories
- Data Structure
- Networking
- RDBMS
- Operating System
- Java
- iOS
- HTML
- CSS
- Android
- Python
- C Programming
- C++
- C#
- MongoDB
- MySQL
- Javascript
- PHP
- Physics
- Chemistry
- Biology
- Mathematics
- English
- Economics
- Psychology
- Social Studies
- Fashion Studies
- Legal Studies

- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who

# 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 actually 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 3 - 6 + 6.

To solve this, we will follow these steps −

- count := an empty map
- Define a function getSum() . This will take 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 do the following
- getSum(root)

Let us see the following implementation to get better understanding −

## Example

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) ob = Solution() root = TreeNode(-6) root.left = TreeNode(3) root.right = TreeNode(6) print(ob.solve(root))

## Input

root = TreeNode(-6) root.left = TreeNode(3) root.right = TreeNode(6)

## Output

3

- Related Articles
- Most Frequent Subtree Sum in C++
- Program to find largest binary search subtree from a given tree in Python
- Python program to find Most Frequent Character in a String
- Find the largest Perfect Subtree in a given Binary Tree in Python
- Find the largest Complete Subtree in a given Binary Tree in Python
- Python Program to Find the Sum of All Nodes in a Binary Tree
- Program to find frequency of the most frequent element in Python
- Program to find largest sum of any path of a binary tree in Python
- Find largest subtree sum in a tree in C++
- Check if a binary tree is subtree of another binary tree in C++
- Program to find sum of longest sum path from root to leaf of a binary tree in Python
- Program to find a tree by updating values with left and right subtree sum with itself in Python
- Program to find sum of all numbers formed by path of a binary tree in python
- Program to find sum each of the diagonal path elements in a binary tree in Python
- Find the largest Complete Subtree in a given Binary Tree in C++

Advertisements