Most Frequent Subtree Sum (LeetCode 508): Solution and Explanation

Medium
Hash Table
Tree
Depth First Search
Binary Tree

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

  1. Create an empty map count and set best = 0.
  2. Write dfs(node): return 0 for a null node, otherwise compute s = node.val + dfs(node.left) + dfs(node.right).
  3. Increase count[s] by one and set best = max(best, count[s]), then return s.
  4. Call dfs(root) and return every key of count whose value equals best.

Step-by-step example

root = [5,2,-3]
  1. 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.
  2. Next the right child -3 is a leaf: s = -3, count[-3] = 1, best stays 1.
  3. Back at the root, both children are done: s = 5 + 2 + (-3) = 4, count[4] = 1.
  4. 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]
Press play on the visualizer and the running line lights up here.

Time and space complexity

Work as the input growsinput size n →steps
Post-order DFS with a frequency map O(n)
Two passes over the map O(n)
Collect then sort O(n log n)
Time

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.

Space

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.