Most Frequent Subtree Sum

Given the root of a binary tree, return the most frequent subtree sum. If there is a tie, return all the values with the highest frequency in any order.

The subtree sum of a node is defined as the sum of all the node values formed by the subtree rooted at that node, including the node itself.

Example 1
        5
       / \
      2  -3
Inputroot = [5,2,-3]
Output[2,-3,4]
The subtree sums are 2, -3, and 4, and all occur once, so all are returned.
Example 2
        5
       / \
      2  -5
Inputroot = [5,2,-5]
Output[2]
The subtree sums are 2, -5, and 2, so 2 is the most frequent subtree sum.

Constraints

  • The number of nodes in the tree is in the range [1, 10^4].
  • -10^5 <= Node.val <= 10^5

Asked at 3 companies

Practice questions like this out loud in a mock coding interview with a live AI interviewer. First one free.

Your Solution

(Ctrl/Cmd + Enter)

Switching Language

Loading template...

Sign in to save your progress

AI code evaluation

Get a correctness verdict, what to keep, what's wrong, and the complexity of your solution.

Sign in to evaluate