LeetcodeJun 29, 2025

Most Frequent Subtree Sum

Hazrat Ali

Leetcode

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:

Input: root = [5,2,-3]
Output: [2,-3,4]

Example 2:

Input: root = [5,2,-5]
Output: [2]


Solution
/**
 * @param {TreeNode} root
 * @return {number[]}
 */
const findFrequentTreeSum = root => {
  if (!root) {
    return [];
  }

  const mapSum = {};
  const mapCount = {};
  let max = 0;

  const helper = node => {
    if (!node) {
      return 0;
    }

    const left = helper(node.left);
    const right = helper(node.right);
    const sum = left + node.val + right;
    const count = ~~mapSum[sum] + 1;

   
    max = Math.max(max, count);

 
    mapSum[sum] = count;

   
    if (!mapCount[count]) {
      mapCount[count] = new Set();
    }
    mapCount[count].add(sum);

    return sum;
  };

  helper(root);

 
  return [...mapCount[max]];
};






Comments