508. Most Frequent Subtree Sum

本文解析了LeetCode上关于求二叉树中最频繁子树和的问题,介绍了使用递归方法结合unordered_map统计子树和及其出现频率的解题技巧。通过实例展示了如何找到并返回出现次数最多的子树和及其值。

The description of the problem

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).

 

来源:力扣(LeetCode)
链接:https://leetcode.cn/problems/most-frequent-subtree-sum

an example

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

The intuition for this problem

the recursive method to add all the substree summarization
use the unordered_map STL to find collect the summary value and its appearance time

The corresponding codes

#include <vector>
#include <iostream>
#include <unordered_map>
using namespace std;
//  Definition for a binary tree node.
 struct TreeNode {
    int val;
    TreeNode *left;
    TreeNode *right;
    TreeNode() : val(0), left(nullptr), right(nullptr) {}
    TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
   TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
};
class Solution {
private:
    unordered_map<int, int> cnt_;
    int max_cnt_;
public:
    vector<int> findFrequentTreeSum(TreeNode* root) {
        vector<int> res;
        tree_sum(root);
        for (auto it = cnt_.begin(); it != cnt_.end(); ++it) {
            if (it->second == max_cnt_) {
                res.emplace_back(it->first);
            }
        }
        return res;
    }
    int tree_sum(TreeNode* root) {
        if(!root) return 0;
        int sum = root->val + tree_sum(root->left) + tree_sum(root->right);
        ++cnt_[sum];
        max_cnt_ = max(max_cnt_, cnt_[sum]);
        return sum;
    }
};
int main() 
{
    Solution s;
    TreeNode* root = new TreeNode(5);
    root->left = new TreeNode(2);
    root->right = new TreeNode(-3);
    root->left->left = new TreeNode(1);
    root->left->right = new TreeNode(3);
    root->right->left = new TreeNode(-2);
    root->right->right = new TreeNode(7);
    auto res = s.findFrequentTreeSum(root);
    cout << "res: ";
    for (auto &i : res) {
        std::cout << i << " ";
    }

    return 0;
}

The result

$ ./test
res: 13 2 7 6 3 -2 1 %

在这里插入图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值