[leetcode]526. Beautiful Arrangement

本文介绍了一种算法,用于找到二叉树中出现频率最高的子树和,并详细解释了如何通过后序遍历来实现这一目标。文章还提供了两种不同的实现方式:一种是在遍历过程中直接更新结果;另一种是先完成遍历后再保存结果。

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

[leetcode]526. Beautiful Arrangement


Analysis

虚惊一场~—— [好好养生!!]

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.
显然应该采用后续遍历,然后记录各个子树sum出现的次数,如果出现了次数更高的sum,则更新结果。

Implement

一边遍历一边更新res

/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
 * };
 */
class Solution {
public:
    vector<int> findFrequentTreeSum(TreeNode* root) {
        vector<int> res;
        int cnt = 0;
        unordered_map<int, int> mymap;
        postOrder(root, res, cnt, mymap);
        return res;
    }
    int postOrder(TreeNode* node, vector<int>& res, int& cnt, unordered_map<int, int>& mymap){
        if(!node)
            return 0;
        int left = postOrder(node->left, res, cnt, mymap);
        int right = postOrder(node->right, res, cnt, mymap);
        int tmp = left+right+node->val;
        mymap[tmp]++;
        if(mymap[tmp]>cnt){
            res.clear();
            res.push_back(tmp);
            cnt = mymap[tmp];
        }
        else if(mymap[tmp] == cnt){
            res.push_back(tmp);
        }
        return tmp;
    }
};

先遍历再保存结果

/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
 * };
 */
class Solution {
public:
    vector<int> findFrequentTreeSum(TreeNode* root) {
        vector<int> res;
        int cnt = 0;
        unordered_map<int, int> mymap;
        postOrder(root, cnt, mymap);
        unordered_map<int, int>::iterator it;
        for(it = mymap.begin(); it!=mymap.end(); it++){
            if(it->second == cnt)
                res.push_back(it->first);
        }
        return res;
    }
    int postOrder(TreeNode* node, int& cnt, unordered_map<int, int>& mymap){
        if(!node)
            return 0;
        int left = postOrder(node->left, cnt, mymap);
        int right = postOrder(node->right, cnt, mymap);
        int tmp = left+right+node->val;
        mymap[tmp]++;
        cnt = max(cnt, mymap[tmp]);
        return tmp;
    }
};
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值