Most Frequent Subtree Sum solution explained
To solve Most Frequent Subtree Sum, do one post-order traversal in which each node returns its own value plus the sums returned by its children, and count every sum in a hash map as it is produced. When the walk finishes, return every sum whose count equals the highest count. Each node is processed once, so it runs in O(n) time and O(n) space.
By Evin JohnPublished 8 min read
Restating the problem
Each node of a binary tree holds an integer, which may be negative or zero. The subtree sum of a node is the total of every value in the subtree rooted there, the node itself included. Every node therefore produces exactly one subtree sum, and different nodes can produce the same one. Find the sum or sums that occur the most times and return them in any order. If several sums tie for the top count, return all of them.
Tree A Tree B
5 4
/ \ / \
2 -5 2 -6
/ \
1 -3
Tree A sums: 1, -3, 0 (at 2), -5, 0 (at 5) -> answer [0]
Tree B sums: 2, -6, 0 (at 4), each once -> answer [2, -6, 0]Tree A shows why negatives make this interesting: the node 2 and the root both total 0 even though they look nothing alike. Tree B shows the tie rule. Every sum occurs once, so all three are returned. A tree with one node returns a list holding that node's value.
Why it comes up
This is a compact test of two habits at once. The first is computing an aggregate bottom-up instead of starting fresh at every node. The second is handling a frequency map carefully: finding the top count, and returning every key that reaches it rather than the first one found. Interviewers often use it as a warm-up before a harder subtree question. Expect variations such as:
- Split the tree into two parts with equal sums by removing one edge. Collect the subtree sums, then check whether half the total appears among them, taking care not to count the whole tree itself.
- Return only the smallest of the tied sums. Same counting, a different final pick.
- Most frequent subtree size or height. Return a different number from each call; the counting is identical.
- Large values. Sums can outgrow 32-bit integers in languages with fixed-width types, so ask about ranges.
- Do it with one pass over the map, or none. Track the best count while counting, as the JavaScript version below does.
Slow version: add up each subtree separately
The straightforward plan visits every node and, for each, runs a separate walk to total its subtree. Then it counts the totals and picks the winners. The total for a node costs the size of its subtree, and every node is inside the subtrees of all its ancestors, so the work is O(n·h): fine for balanced trees, quadratic for a chain. It is easy to trust, which is why it serves as our reference in tests.
class TreeNode:
def __init__(self, val=0, left=None, right=None):
self.val = val
self.left = left
self.right = right
def subtree_total(node):
if node is None:
return 0
return node.val + subtree_total(node.left) + subtree_total(node.right)
def most_frequent_sums_slow(root):
freq = {}
stack = [root] if root else []
while stack:
node = stack.pop()
s = subtree_total(node)
freq[s] = freq.get(s, 0) + 1
if node.left:
stack.append(node.left)
if node.right:
stack.append(node.right)
if not freq:
return []
top = max(freq.values())
return [s for s, c in freq.items() if c == top]Linear version: let children report their sums
A node's subtree sum is its value plus its left child's subtree sum plus its right child's. If the children are finished first, the parent needs only two additions. Post-order is exactly that order, so a recursive function that returns the sum of its subtree computes every sum in one pass, and it can record each one in a counter on the way out. An empty child returns 0 and is not counted, since it is not a node.
from collections import Counter
def most_frequent_sums(root):
if root is None:
return []
freq = Counter()
def total(node):
if node is None:
return 0
s = node.val + total(node.left) + total(node.right)
freq[s] += 1
return s
total(root)
top = max(freq.values())
return [s for s, c in freq.items() if c == top]The recursion depth equals the tree height, so a very lopsided tree of more than about a thousand nodes needs Python's recursion limit raised or an iterative rewrite. The JavaScript version is the iterative rewrite: it builds a parent-before-child list, processes it backward so both children are done before their parent, and keeps the best count as it goes. When a sum beats the best count, the winners list restarts; when it ties, the sum joins the list.
function findFrequentTreeSum(root) {
if (root === null) return [];
const order = [];
const stack = [root];
while (stack.length > 0) {
const node = stack.pop();
order.push(node);
if (node.left !== null) stack.push(node.left);
if (node.right !== null) stack.push(node.right);
}
const sumOf = new Map();
const freq = new Map();
let best = 0;
let winners = [];
for (let i = order.length - 1; i >= 0; i--) {
const node = order[i];
const left = node.left === null ? 0 : sumOf.get(node.left);
const right = node.right === null ? 0 : sumOf.get(node.right);
const s = node.val + left + right;
sumOf.set(node, s);
const times = (freq.get(s) || 0) + 1;
freq.set(s, times);
if (times > best) {
best = times;
winners = [s];
} else if (times === best) {
winners.push(s);
}
}
return winners;
}Why does the running list stay correct? A sum enters the list when its count first equals the best, and the list is cleared whenever any count passes the best, so at the end it holds exactly the sums whose final count equals the final best. No sum can be added twice, because once a sum is in the list, its next increment either raises the best (clearing the list) or exceeds it.
Trace Tree A. Leaves 1 and -3 report themselves. Node 2 reports 2 + 1 - 3 = 0. Leaf -5 reports -5. The root reports 5 + 0 - 5 = 0. Counts: 1 once, -3 once, 0 twice, -5 once, so the answer is [0].
Complexity
| Approach | Time | Extra space |
|---|---|---|
| Recompute each subtree sum | O(n·h), O(n²) worst case | O(h) stack plus O(n) counts |
| Post-order sums, then scan the counter | O(n) | O(n) counts plus O(h) stack |
| Iterative post-order, winners kept during the pass | O(n) | O(n) for the order list and maps |
Edge cases
- One node: return [its value].
- All sums distinct: every sum is returned.
- Negative values that cancel, so unrelated nodes share a sum of 0.
- Zero-valued nodes: a chain of zeros gives the same sum n times.
- An empty tree, if allowed: return an empty list rather than call max on nothing.
- Large magnitudes: confirm the sum type in typed languages.
Typical mistakes
- Returning only one of several tied sums.
- Counting the 0 that an empty child returns, which inflates the count of 0 on every tree with a leaf.
- Storing sums per value instead of per node, so two nodes with the same value share one sum.
- Computing the most frequent node value rather than the most frequent subtree sum.
- Clearing the winners list on a tie instead of appending.
Explaining it in the room
Fictional example
- Candidate
- A node's subtree sum is its value plus its children's subtree sums, so I want the children done first. Post-order gives me that.
- Candidate
- My helper returns the sum and counts it in a map. Empty children return zero but are not counted, because they are not nodes.
- Interviewer
- What about ties?
- Candidate
- I return every sum whose count equals the maximum. Either I scan the map at the end, or I keep a winners list during the walk and reset it when a count beats the best.
- Candidate
- Each node is handled once, so it is O(n) time, and the map holds at most n sums.
Related walkthroughs
Find Duplicate Subtrees counts subtrees by their full shape rather than by a single number. Diameter of N-ary Tree returns heights in the same post-order style, and Pseudo-Palindromic Paths in a Binary Tree passes state the other way, from root to leaves. Sum Root to Leaf Numbers is the top-down cousin of this problem.
Natively in your practice
If you work through tree problems on a Mac or Windows computer, Natively can read the prompt from a screenshot and show an approach and working code in its overlay, or just answer a narrow question like how to keep the tied winners in one pass. Talk through your solution during a mock round and it keeps a transcript you can reread for gaps, such as skipping the empty-child rule. The AI interview assistant page has the details.
Questions people ask
How do you solve Most Frequent Subtree Sum?
Run a post-order traversal where each node returns its value plus its children's sums, count each sum in a hash map, and return every sum whose count equals the highest count.
What does Most Frequent Subtree Sum return when there is a tie?
All of the tied sums, in any order. If every sum appears once, every sum is returned.
What is the time complexity of Most Frequent Subtree Sum?
O(n) time because each node's sum is built from its children's sums in constant time, and O(n) space for the frequency map.
Should an empty child count as a subtree sum of 0?
No. Empty children return 0 so the parent's arithmetic works, but they are not nodes, so their 0 is never counted.
Where to go next
Practice with the same assistant you would use on a call: it listens, transcribes and suggests answers from your own resume and the job description.
Facts on this page were last checked on . Product details come from the Natively app itself; if something here is out of date, tell us at hello@heynatively.com.
