Most Frequent Subtree Sum (LeetCode 508): Solution and Explanation
Every node defines a subtree, and every subtree has a sum. Return the sum that shows up most often across all nodes, or every sum that ties for the top count.
Intuition
The sum of a subtree is the node's value plus the sums of its left and right subtrees. If the children's sums are already known, the parent's sum costs one addition.
A post-order DFS gives exactly that order: both children return their sums before the parent computes its own. Each node's sum is produced once.
As each sum appears, count it in a hash map and remember the highest count seen. A final pass over the map collects every sum that reached that count.
Approach: Post-order DFS with a frequency map
- Create an empty map
countand setbest = 0. - Write
dfs(node): return 0 for a null node, otherwise computes = node.val + dfs(node.left) + dfs(node.right). - Increase
count[s]by one and setbest = max(best, count[s]), then returns. - Call
dfs(root)and return every key ofcountwhose value equalsbest.
Step-by-step example
root = [5,2,-3]
- dfs(5) first recurses into the left child 2. It is a leaf, so s = 2 + 0 + 0 = 2 and count[2] = 1, best = 1.
- Next the right child -3 is a leaf: s = -3, count[-3] = 1, best stays 1.
- Back at the root, both children are done: s = 5 + 2 + (-3) = 4, count[4] = 1.
- The map holds 2, -3 and 4, each seen once. All three equal best, so return [2,-3,4].
Code: Python, Java, C++
1class Solution:
2 def findFrequentTreeSum(self, root: Optional[TreeNode]) -> List[int]:
3 count = {}
4 best = 0
5
6 def dfs(node):
7 nonlocal best
8 if not node:
9 return 0
10 s = node.val + dfs(node.left) + dfs(node.right)
11 count[s] = count.get(s, 0) + 1
12 best = max(best, count[s])
13 return s
14
15 dfs(root)
16 return [s for s, c in count.items() if c == best]1class Solution {
2 private Map<Integer, Integer> count;
3 private int best;
4
5 public int[] findFrequentTreeSum(TreeNode root) {
6 count = new LinkedHashMap<>();
7 best = 0;
8 dfs(root);
9 List<Integer> res = new ArrayList<>();
10 for (Map.Entry<Integer, Integer> e : count.entrySet()) {
11 if (e.getValue() == best) res.add(e.getKey());
12 }
13 int[] ans = new int[res.size()];
14 for (int i = 0; i < ans.length; i++) ans[i] = res.get(i);
15 return ans;
16 }
17
18 private int dfs(TreeNode node) {
19 if (node == null) return 0;
20 int s = node.val + dfs(node.left) + dfs(node.right);
21 count.merge(s, 1, Integer::sum);
22 best = Math.max(best, count.get(s));
23 return s;
24 }
25}1class Solution {
2 unordered_map<int, int> count;
3 vector<int> order;
4 int best = 0;
5
6 int dfs(TreeNode* node) {
7 if (!node) return 0;
8 int s = node->val + dfs(node->left) + dfs(node->right);
9 if (count[s]++ == 0) order.push_back(s);
10 best = max(best, count[s]);
11 return s;
12 }
13
14public:
15 vector<int> findFrequentTreeSum(TreeNode* root) {
16 count.clear();
17 order.clear();
18 best = 0;
19 dfs(root);
20 vector<int> res;
21 for (int s : order) {
22 if (count[s] == best) res.push_back(s);
23 }
24 return res;
25 }
26};Time and space complexity
O(n)
Each node is visited once and does a constant amount of hash map work. The final scan touches at most n distinct sums.
O(n)
The map can hold up to n distinct sums, and the recursion stack grows with the tree height h.
Other approaches
Collect then sort (time O(n log n), space O(n))
Store every subtree sum in a list, sort it, and find the longest runs of equal values. It works but sorting adds a log factor.
Two passes over the map (time O(n), space O(n))
Skip tracking best during the DFS and instead take the maximum of the map values afterward, then filter. Same complexity, one extra pass.
Common mistakes
- Computing each node's sum with a separate traversal, which costs O(n^2) on a skewed tree.
- Returning only one sum when several sums tie for the highest count.
- Forgetting that values can be negative, so a sum of 0 or a repeated sum can come from very different subtrees.
Frequently asked questions
Why post-order and not pre-order?
A parent's sum depends on both children's sums. Post-order finishes the children before the parent, so each sum is computed with one addition.
Does the order of the returned sums matter?
No. Any order is accepted. This solution returns them in the order each sum first appeared during the DFS.
Can a subtree sum overflow a 32-bit int?
No. At most 10^4 nodes with absolute values up to 10^5 give sums within plus or minus 10^9, which fits in a 32-bit int.