508. Most Frequent Subtree Sum
MediumSolutions in Python, Java, C++, TypeScript
Read the full problem statement on LeetCode and try it first. Below is how to approach it in an interview, followed by a complete answer in each language.
Approach
The problem asks us to find the most frequent subtree sum in a binary tree. A subtree sum for a node is the sum of its own value and all the values in its left and right subtrees. If there's a tie for the most frequent sum, we should return all sums with that highest frequency.
Solution
Most Frequent Subtree Sum in Python
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, val=0, left=None, right=None):
# self.val = val
# self.left = left
# self.right = right
from collections import Counter
class Solution:
def findFrequentTreeSum(self, root: Optional[TreeNode]) -> List[int]:
if not root:
return []
# Use a Counter to store frequencies of subtree sums
counts = Counter()
# Helper function to perform post-order traversal.
# It returns the sum of the subtree rooted at 'node'.
def post_order(node: Optional[TreeNode]) -> int:
if not node:
return 0
# Recursively find sums of left and right subtrees
left_sum = post_order(node.left)
right_sum = post_order(node.right)
# Calculate current subtree sum
current_sum = node.val + left_sum + right_sum
# Increment the count for this sum
counts[current_sum] += 1
# Return sum to parent call
return current_sum
# Start the traversal from the root
post_order(root)
# Find the maximum frequency. Since root is not None and counts will not be empty,
# we can safely call max on its values.
max_freq = max(counts.values())
# Collect all sums that have the maximum frequency
result = [s for s, freq in counts.items() if freq == max_freq]
return result
Most Frequent Subtree Sum in Java
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode() {}
* TreeNode(int val) { this.val = val; }
* TreeNode(int val, TreeNode left, TreeNode right) {
* this.val = val;
* this.left = left;
* this.right = right;
* }
* }
*/
class Solution {
private Map<Integer, Integer> sumCounts;
private int maxFreq;
public int[] findFrequentTreeSum(TreeNode root) {
// Initialize map and max frequency for each call
sumCounts = new HashMap<>();
maxFreq = 0;
// Start post-order traversal to populate the sumCounts map
postOrder(root);
// Find all sums that have the maximum frequency
List<Integer> resultList = new ArrayList<>();
for (Map.Entry<Integer, Integer> entry : sumCounts.entrySet()) {
if (entry.getValue() == maxFreq) {
resultList.add(entry.getKey());
}
}
// Convert the list of results to an int array
int[] result = new int[resultList.size()];
for (int i = 0; i < resultList.size(); i++) {
result[i] = resultList.get(i);
}
return result;
}
// Helper function to perform post-order traversal
// It returns the sum of the subtree rooted at 'node'
private int postOrder(TreeNode node) {
if (node == null) {
return 0;
}
// Recursively find the sum of left and right subtrees
int leftSum = postOrder(node.left);
int rightSum = postOrder(node.right);
// Calculate the sum of the current subtree
int currentSum = node.val + leftSum + rightSum;
// Increment the frequency of the current sum
int count = sumCounts.getOrDefault(currentSum, 0) + 1;
sumCounts.put(currentSum, count);
// Update the maximum frequency found so far
maxFreq = Math.max(maxFreq, count);
// Return the sum of the current subtree to the parent
return currentSum;
}
}
Most Frequent Subtree Sum in C++
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode() : val(0), left(nullptr), right(nullptr) {}
* TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
* TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
* };
*/
class Solution {
public:
vector<int> findFrequentTreeSum(TreeNode* root) {
sumCounts.clear();
maxFreq = 0;
postOrderTraversal(root);
vector<int> result;
for (auto const& [sum, freq] : sumCounts) {
if (freq == maxFreq) {
result.push_back(sum);
}
}
return result;
}
private:
unordered_map<int, int> sumCounts;
int maxFreq = 0;
// Helper function to perform post-order traversal
// It returns the sum of the subtree rooted at 'node'
int postOrderTraversal(TreeNode* node) {
if (!node) {
return 0;
}
// Recursively find the sum of left and right subtrees
int leftSum = postOrderTraversal(node->left);
int rightSum = postOrderTraversal(node->right);
// Calculate the sum of the current subtree
int currentSum = node->val + leftSum + rightSum;
// Increment the frequency of the current sum
sumCounts[currentSum]++;
// Update the maximum frequency found so far
maxFreq = max(maxFreq, sumCounts[currentSum]);
// Return the sum of the current subtree to the parent
return currentSum;
}
};
Most Frequent Subtree Sum in TypeScript
/**
* Definition for a binary tree node.
* class TreeNode {
* val: number
* left: TreeNode | null
* right: TreeNode | null
* constructor(val?: number, left?: TreeNode | null, right?: TreeNode | null) {
* this.val = (val===undefined ? 0 : val)
* this.left = (left===undefined ? null : left)
* this.right = (right===undefined ? null : right)
* }
* }
*/
function findFrequentTreeSum(root: TreeNode | null): number[] {
if (!root) {
return [];
}
const sumCounts = new Map<number, number>();
let maxFreq = 0;
// Helper function to perform post-order traversal.
// It returns the sum of the subtree rooted at 'node'.
const postOrder = (node: TreeNode | null): number => {
if (!node) {
return 0;
}
// Recursively find sums of left and right subtrees
const leftSum = postOrder(node.left);
const rightSum = postOrder(node.right);
// Calculate the sum of the current subtree
const currentSum = node.val + leftSum + rightSum;
// Increment the frequency of the current sum
const count = (sumCounts.get(currentSum) || 0) + 1;
sumCounts.set(currentSum, count);
// Update the maximum frequency found so far
if (count > maxFreq) {
maxFreq = count;
}
// Return sum to parent call
return currentSum;
};
// Start the traversal from the root
postOrder(root);
const result: number[] = [];
// Iterate through the map to find sums with maximum frequency
for (const [sum, freq] of sumCounts.entries()) {
if (freq === maxFreq) {
result.push(sum);
}
}
return result;
}
More Medium LeetCode answers
Preparing for interviews beyond LeetCode? Practise system design, SQL and behavioral questions with an in-browser runner on KatInterview.
LeetCode is a trademark of LeetCode LLC. KatInterview is not affiliated with LeetCode.