508. Most Frequent Subtree Sum

本文介绍了一种算法,用于找到给定树中出现频率最高的子树和,并提供了详细的实现步骤及示例。通过使用哈希映射记录每个子树和的出现次数,再运用桶排序找出最高频次的子树和。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

Given the root of a tree, you are asked to find the most frequent subtree sum. 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). So what is the most frequent subtree sum value? If there is a tie, return all the values with the highest frequency in any order.

Examples 1
Input:

  5
 /  \
2   -3
return [2, -3, 4], since all the values happen only once, return all of them in any order.

Examples 2
Input:

  5
 /  \
2   -5
return [2], since 2 happens twice, however -5 only occur once.

Note: You may assume the sum of values in any subtree is in the range of 32-bit signed integer.

建立hashmap,存下来所有子树的subsum和subsum出现的次数count。之后用bucket sort找出出现次数最多的subsum。代码如下:

/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
public class Solution {
    HashMap<Integer, Integer> map = new HashMap<Integer, Integer>();
    int count = 0;
    
    public int[] findFrequentTreeSum(TreeNode root) {
        int[] res = new int[0];
        if (root == null) {
            return res;
        }
        helper(root);
        List<Integer>[] list = new List[count + 1];
        for (int num: map.keySet()) {
            int sumcount = map.get(num);
            if (list[sumcount] == null) {
                list[sumcount] = new ArrayList<Integer>();
            }
            list[sumcount].add(num);
        }
        for (int i = count; i >= 0; i --) {
            if (list[i] != null) {
                res = new int[list[i].size()];
                for (int j = 0; j < list[i].size(); j ++) {
                    res[j] = list[i].get(j);
                }
                break;
            }
        }
        return res;
    }
    
    private int helper(TreeNode root) {
        if (root == null) {
            return 0;
        }
        int subsum = helper(root.left) + helper(root.right) + root.val;
        map.put(subsum, map.getOrDefault(subsum, 0) + 1);
        count ++;
        return subsum;
    }
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值