Skip to content
Problem 508 · LeetCode 508(opens in a new tab)

Most Frequent Subtree Sum

MediumDepth-first search

You get the root of a binary tree. The subtree sum of a node is the total of every value in the subtree that hangs from it, the node's own value included.

Every node has one subtree sum. Find the sum that occurs most often across all nodes. If several sums tie for the most, return all of them, in any order.

Example 1

Input:  root = [3, -2, 2, 2]
Output: [2]
Why:    the sums are 2, 0, 2 and 5, and only 2 appears twice
2 more examples and the constraints

Example 2

Input:  root = [4, 1, -5]
Output: [1, -5, 0]
Why:    the sums 1, -5 and 0 each appear once, so all three tie

Example 3

Input:  root = [6]
Output: [6]
Why:    the only node has sum 6

Constraints

  • The tree has 1 to 10,000 nodes.
  • -100,000 ≤ Node.val ≤ 100,000

Your turn first

Have a go on paper or in your own editor, then reveal the approaches from the simplest up.

Try it on LeetCode(opens in a new tab)
  1. Re-sum every subtreeO(n²)
  2. Post-order with a counterO(n)

The idea in one sentence

The pattern, how to spot it, and the best complexity.

Side by side

ApproachTimeRelative work for a 10,000-node chainVerdict
Re-sum every subtreeO(n²)
Simple, redoes every sum
Post-order with a counterO(n)
Best; each sum built once

n = number of nodes, h = height of the tree.

Edge cases to test

  • One node. [6] gives [6]: one sum, seen once.
  • Every sum different. [4, 1, -5] gives all three sums, since they tie at one each.
  • Zero sums. [0, 0, 0] gives [0]; a sum of 0 is a real sum, not a missing one.
  • Negative values. Sums can be negative, such as -100,000 for a leaf, so do not use them as array indexes.
  • Deep chain. A chain-shaped tree makes the recursion as deep as the number of nodes.

Common mistakes

  • Returning only one sum when several tie for the highest count.
  • Counting a sum before the children are finished, which means pre-order with wrong totals.
  • Skipping the leaves, whose subtree sum is just their own value.

How to talk through it

  1. 1Clarify. Does a node's own value count in its sum? How should ties be returned?
  2. 2Give the brute force. Re-sum each node's subtree from scratch: O(n²) for a chain.
  3. 3Return the sum upward. Post-order: each call returns its sum, so the parent adds two numbers.
  4. 4Count and collect. A hash map of sum to count, then every sum with the top count.
  5. 5Test out loud. Run a single node and a tree where every sum ties.
Was this problem useful?Your vote tells us what to improve next.
Found a bug in our code, or something unclear?