Most Frequent Subtree Sum - Problem

Given the root of a binary tree, return the most frequent subtree sum. If there is a tie, return all the values with the highest frequency in any order.

The subtree sum of a node is defined as the sum of all the node values formed by the subtree rooted at that node (including the node itself).

Input & Output

Example 1 — Basic Tree
$ Input: root = [5,2,-3]
Output: [2,-3,4]
💡 Note: Subtree sums: Node 2 has sum 2, Node -3 has sum -3, Node 5 has sum 5+2+(-3)=4. All appear once, so return all.
Example 2 — Duplicate Sums
$ Input: root = [5,2,-5]
Output: [2]
💡 Note: Subtree sums: Node 2 has sum 2, Node -5 has sum -5, Node 5 has sum 5+2+(-5)=2. Sum 2 appears twice (most frequent), so return [2].
Example 3 — Single Node
$ Input: root = [1]
Output: [1]
💡 Note: Only one subtree with sum 1, so it's the most frequent.

Constraints

  • The number of nodes in the tree is in the range [1, 104]
  • -105 ≤ Node.val ≤ 105

Visualization

Tap to expand
Most Frequent Subtree Sum Problem52-3Step 1: Input TreeSubtree Sums:Node 2: 2Node -3: -3Node 5: 4Step 2: Calculate SumsStep 3: All frequencies equal (1)Result: [2, -3, 4]
Understanding the Visualization
1
Input Tree
Binary tree with node values
2
Calculate Sums
Find sum for each subtree
3
Find Most Frequent
Return sums that appear most often
Key Takeaway
🎯 Key Insight: Use post-order DFS to calculate subtree sums efficiently while tracking frequencies in a single pass
Asked in
Amazon 15 Google 12 Facebook 8
32.0K Views
Medium Frequency
~15 min Avg. Time
892 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