The Most Frequent Subtree Sum problem gives you a binary tree where each node has an integer value. A subtree sum is the sum of all values in a subtree rooted at some node. Find the most frequently occurring subtree sum(s). If there are ties, return all of them. This Most Frequent Subtree Sum coding problem uses DFS with a frequency map.
Amazon and Bloomberg ask this because it combines DFS tree traversal with frequency counting — two fundamental skills that appear throughout data structure interviews. It tests the ability to pass computed values up a recursive tree (post-order DFS) and efficiently track result frequencies. The hash table, DFS, binary tree, and tree interview pattern is the core.
Post-order DFS + frequency map. For each node, recursively compute the left subtree sum and right subtree sum. The subtree sum at the current node = node.val + left_sum + right_sum. Update a global frequency map with this sum. After the DFS completes, find and return all sums with the maximum frequency.
Tree:
5
/ \
2 -3
Post-order DFS problems compute values bottom-up: process children first, then use their results for the parent. This pattern appears in subtree height, subtree size, path sum, and LCA problems. Practice writing the post-order DFS template: recurse left, recurse right, then compute result for current node. Frequency map tracking alongside recursion is a common pattern — returning the max-frequency keys is a standard post-processing step.
| Title | Difficulty | Topics | LeetCode |
|---|---|---|---|
| Find Duplicate Subtrees | Medium | Solve | |
| Lowest Common Ancestor of a Binary Tree IV | Medium | Solve | |
| Lowest Common Ancestor of Deepest Leaves | Medium | Solve | |
| Clone Binary Tree With Random Pointer | Medium | Solve | |
| Find Distance in a Binary Tree | Medium | Solve |