LeetCode

来源:互联网 发布:知乎什么时候成立的 编辑:程序博客网 时间:2024/06/10 14:30


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.


问在一棵二叉树中,子树和最多的值是多少,如果有多个,返回多个。

用一个map存一下数量,最后遍历map更新ans,时间复杂度O(n)。

/** * 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> ans;        if (!root) return ans;        unordered_map<int, int> cnt;        int mmax = 0;        solve(root, cnt, mmax);                for (auto x: cnt) {            if (x.second == mmax)                ans.push_back(x.first);        }        return ans;    }    int solve(TreeNode* root, unordered_map<int, int> &cnt, int &mmax) {        if (!root) return 0;        int sum = root->val;        sum += solve(root->left, cnt, mmax) + solve(root->right, cnt, mmax);        cnt[sum]++;        mmax = max(cnt[sum], mmax);        return sum;    }};