Most Frequent Subtree Sum - Problem
You are given the root of a binary tree and need to find the most frequent subtree sum(s). A subtree sum is calculated by adding up all the values of nodes in a subtree rooted at a particular node (including the node itself).

Your task is to return all subtree sums that appear most frequently. If there's a tie between multiple sums having the same highest frequency, return all of them in any order.

Example: If a tree has subtree sums [2, -3, 4, 2, -3, 2], then the sum 2 appears 3 times (most frequent), so we return [2]. If both 2 and -3 appeared 3 times each, we'd return [2, -3].

This problem combines tree traversal with frequency counting - a common pattern in coding interviews!

Input & Output

example_1.py โ€” Basic Tree
$ Input: root = [5,2,-3,null,null,null,4]
โ€บ Output: [2, -3, 4]
๐Ÿ’ก Note: Subtree sums are: Node 5: 5+2+(-3)+4=8, Node 2: 2, Node -3: -3+4=1, Node 4: 4. Each sum appears once, so all are most frequent.
example_2.py โ€” Repeated Sums
$ Input: root = [5,2,-5]
โ€บ Output: [2]
๐Ÿ’ก Note: Subtree sums are: Node 5: 5+2+(-5)=2, Node 2: 2, Node -5: -5. Sum 2 appears twice (most frequent), so return [2].
example_3.py โ€” Single Node
$ Input: root = [1]
โ€บ Output: [1]
๐Ÿ’ก Note: Only one node with value 1, so subtree sum is 1, appearing once. Return [1].

Visualization

Tap to expand
52-324Sum: 2Sum: 4Sum: 2+2=4Sum: -3+4=1Sum: 5+4+1=10Frequency Map2: appears 1 time4: appears 2 times โœ“1: appears 1 time10: appears 1 time
Understanding the Visualization
1
Start at Leaves
Begin with leaf nodes (people with no children) - their subtree sum is just their own value
2
Move Up Levels
For each parent node, add their value to the sum of all their children's subtree sums
3
Track Frequencies
Keep count of how many times each subtree sum appears using a hash map
4
Find Maximum
Return all sums that appear most frequently in the tree
Key Takeaway
๐ŸŽฏ Key Insight: Post-order traversal ensures we calculate children's sums before parents, making each subtree sum calculation efficient in O(1) time per node.

Time & Space Complexity

Time Complexity
โฑ๏ธ
O(n)

Single traversal visiting each node exactly once

n
2n
โœ“ Linear Growth
Space Complexity
O(n)

Hash map for frequencies plus O(h) recursion stack where h is tree height

n
2n
โšก Linearithmic Space

Constraints

  • The number of nodes in the tree is in the range [1, 104]
  • -105 โ‰ค Node.val โ‰ค 105
  • Follow up: Can you solve it without using extra space for the frequency map?
Asked in
Google 45 Amazon 38 Facebook 32 Microsoft 28
76.3K Views
Medium Frequency
~18 min Avg. Time
1.8K Likes
Ln 1, Col 1
Smart Actions
๐Ÿ’ก Explanation
AI Ready
๐Ÿ’ก Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen