1. 程式人生 > >508. Most Frequent Subtree Sum(python+cpp)

508. Most Frequent Subtree Sum(python+cpp)

題目:

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.

解釋:
這種問題,很明顯要避免重複計算,所以要在dfs的時候做一些記錄和更新。
python程式碼:

# Definition for a binary tree node.
# class TreeNode(object):
#     def __init__(self, x):
#         self.val = x
#         self.left = None
#         self.right = None

class Solution(object):
    def findFrequentTreeSum(self, root):
        """
        :type root: TreeNode
        :rtype: List[int]
        """
_dict={} #求當前root下的子樹和,子樹和出現的次數用字典存 def dfs(root): if not root: return 0 temp=0 temp+=root.val if root.left: temp+=dfs(root.left) if root.right: temp+=dfs(root.right) _dict[temp]=_dict.get(temp,0)+1 return temp if not root: return [] dfs(root) #感覺這裡可以省時間 result=[] max_val=1 for key in _dict: if _dict[key]==max_val: result.append(key) elif _dict[key]>max_val: max_val=_dict[key] result=[key] return result

c++程式碼:

/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
 * };
 */
#include <map>
using namespace std;
class Solution {
public:
    map<int,int>countofSum;
    vector<int> findFrequentTreeSum(TreeNode* root) {
        vector<int> result;
        if(!root)
            return result;
        getSum(root);
        int max_val=1;
        for(auto item:countofSum)
        {
            if (item.second==max_val)
                result.push_back(item.first);
            else if(item.second>max_val)
            {
                max_val=item.second;
                result={item.first};
            }  
        }
        return result;
    }
    int getSum(TreeNode* root)
    {
        if(!root)
            return NULL;
        int tmpSum=root->val;
        if(root->left)
            tmpSum+=getSum(root->left);
        if(root->right)
            tmpSum+=getSum(root->right);
        countofSum[tmpSum]+=1;
        return tmpSum;
    }
};

總結:
需要注意的就是在遍歷的過程中更新map,這樣可以有效避免重複計算。