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 INPUT Binary Tree Structure 5 2 -3 Array Representation: 5 2 -3 root = [5, 2, -3] 3 nodes total ALGORITHM STEPS 1 DFS Traversal Post-order: left, right, root 2 Calculate Subtree Sum sum = node + left + right 3 Track Frequency HashMap: sum --> count 4 Find Max Frequency Return all with max freq Subtree Sum Calculations: Node 2: sum = 2 freq: 1 Node -3: sum = -3 freq: 1 Node 5: sum = 5+2+(-3) = 4 freq: 1 All sums have frequency = 1 Return all: [2, -3, 4] FINAL RESULT Subtree Sums Visualization 5 sum:4 2 sum:2 -3 sum:-3 Output Array: 2 -3 4 OK - All sums returned! Max frequency = 1 3 sums with freq 1 Key Insight: Use post-order DFS to compute subtree sums bottom-up. Each node's subtree sum = node value + left subtree sum + right subtree sum. Track frequency with HashMap, then find max frequency sums. Time: O(n), Space: O(n) for recursion stack and frequency map. TutorialsPoint - Most Frequent Subtree Sum | Optimized DFS with Frequency Tracking
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