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

<p>The <strong>subtree sum</strong> 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).</p>

<p>&nbsp;</p>
<p><strong class="example">Example 1:</strong></p>
<img alt="" src="https://assets.leetcode.com/uploads/2021/04/24/freq1-tree.jpg" style="width: 207px; height: 183px;" />
<pre>
<strong>Input:</strong> root = [5,2,-3]
<strong>Output:</strong> [2,-3,4]
</pre>

<p><strong class="example">Example 2:</strong></p>
<img alt="" src="https://assets.leetcode.com/uploads/2021/04/24/freq2-tree.jpg" style="width: 207px; height: 183px;" />
<pre>
<strong>Input:</strong> root = [5,2,-5]
<strong>Output:</strong> [2]
</pre>

<p>&nbsp;</p>
<p><strong>Constraints:</strong></p>

<ul>
	<li>The number of nodes in the tree is in the range <code>[1, 10<sup>4</sup>]</code>.</li>
	<li><code>-10<sup>5</sup> &lt;= Node.val &lt;= 10<sup>5</sup></code></li>
</ul>

/**
 * 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:
    int collect(TreeNode* root, std::vector<int>* sums) {
        if (root == nullptr) {
            return 0;
        }
        int sum = collect(root->left, sums) + collect(root->right, sums) + root->val;
        sums->push_back(sum);
        return sum;
    }
public:
    vector<int> findFrequentTreeSum(TreeNode* root) {
        if (root == nullptr) {
            return std::vector<int>();
        }
        std::vector<int> sums;
        collect(root, &sums);
        std::sort(sums.begin(), sums.end());
        int current = sums[0];
        int count = 1;
        std::vector<std::pair<int, int>> counts;
        for (int i=1; i<sums.size(); ++i) {
            if (sums[i] != current) {
                counts.push_back({count, current});
                count = 1;
                current = sums[i];
            } else {
                ++ count;
            }
        }
        counts.push_back({count, current});
        std::sort(counts.begin(), counts.end(), std::greater<std::pair<int, int>>());
        std::vector<int> result;
        result.push_back(counts[0].second);
        count = counts[0].first;
        for (int i=1; i<counts.size() && counts[i].first == count; ++i) {
            result.push_back(counts[i].second);
        }
        return result;
    }
};
21900