[leetcode]526. Beautiful Arrangement

[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;
    }
};

猜你喜欢

转载自blog.csdn.net/weixin_32135877/article/details/82389489