508. Most Frequent Subtree Sum

https://leetcode.com/problems/most-frequent-subtree-sum/

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.

/**
 * 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) {}
 * };
 */

算法思路:

直接抄501. Find Mode in Binary Search Tree方法一的通用代码

class Solution {
public:
    vector findFrequentTreeSum(TreeNode* root) {
        vector arr;
        caculateTreeSum(root, arr);
        int count = 0;
        unordered_map um;
        for (auto& x : arr) {
            um[x]++;
            count = max(count, um[x]);
        }
        vector res;
        for (auto& pair : um) {
            if (pair.second == count) {
                res.push_back(pair.first);
            }
        }
        return res;
    }
private:
    int caculateTreeSum(TreeNode* node, vector& arr) {
        if (node == nullptr) return 0;
        int sum = node->val + caculateTreeSum(node->left, arr) + caculateTreeSum(node->right, arr);
        arr.push_back(sum);
        return sum;
    }
};

改进下,一开始直接存入map,少一步vector到map的转换过程

class Solution {
public:
    vector findFrequentTreeSum(TreeNode* root) {
        int count = 0;
        unordered_map um;
        caculateTreeSum(root, um, count);
        vector res;
        for (auto& pair : um) {
            if (pair.second == count) {
                res.push_back(pair.first);
            }
        }
        return res;
    }
private:
    int caculateTreeSum(TreeNode* node, unordered_map& um, int& count) {
        if (node == nullptr) return 0;
        int sum = node->val + caculateTreeSum(node->left, um, count) 
                            + caculateTreeSum(node->right, um, count);
        count = max(count, ++um[sum]);
        return sum;
    }
};

 

你可能感兴趣的:(leetcode)