Given the root of a binary tree, return the most frequent subtree sum. A subtree sum is defined as the sum of all the node values in that subtree, including the root. If there is a tie in the frequency of the sums, you should return all of them.
What is the structure of the tree nodes?
The tree nodes are likely structured using a standard TreeNode
class with attributes for value, left child, and right child.
Can the tree contain negative values? Yes, the tree can contain both positive and negative values.
Is there a limit on the tree’s size? No explicit limit is given, but it should be reasonable to handle in memory.
Would the tree always contain at least one node? Yes, per the problem definition, there is always at least the root node.
from collections import defaultdict
from typing import List, Optional
# 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
class Solution:
def findFrequentTreeSum(self, root: Optional[TreeNode]) -> List[int]:
if not root:
return []
sum_count = defaultdict(int)
def dfs(node):
if not node:
return 0
# Calculate the subtree sum
left_sum = dfs(node.left)
right_sum = dfs(node.right)
subtree_sum = node.val + left_sum + right_sum
# Record the sum in the frequency map
sum_count[subtree_sum] += 1
return subtree_sum
# Initiate the DFS traversal from the root
dfs(root)
# Find the maximum frequency of the subtree sums
max_frequency = max(sum_count.values())
# Collect all the sums with the maximum frequency
most_frequent_sums = [s for s, freq in sum_count.items() if freq == max_frequency]
return most_frequent_sums
This solution is efficient and should work well within typical constraints for binary tree problems.
Got blindsided by a question you didn’t expect?
Spend too much time studying?
Or simply don’t have the time to go over all 3000 questions?