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
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
💡
Explanation
AI Ready
💡 Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code