508. Most Frequent Subtree Sum 最頻繁的子樹和

[抄題]:node

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:app

  5
 /  \
2   -5

 

 [暴力解法]:ide

時間分析:post

空間分析:優化

 [優化後]:spa

時間分析:debug

空間分析:

[奇葩輸出條件]:

[奇葩corner case]:

[思惟問題]:

不知道怎麼存儲maxCount:單獨加個變量就好了,何況加變量也不費事啊。

[英文數據結構或算法,爲何不用別的數據結構或算法]:

要求返回數組,不能直接添加,須要間接添加到List<Integer> res中。

[一句話思路]:

[輸入量]:空: 正常狀況:特大:特小:程序裏處理到的特殊狀況:異常狀況(不合法不合理的輸入):

[畫圖]:

[一刷]:

int left = postOrder(root.left); 要求前序遍歷有返回值的時候,從void類型改爲int類型,隨機應變。雖然是int型,能夠不返回,直接調用。

[二刷]:

[三刷]:

[四刷]:

[五刷]:

  [五分鐘肉眼debug的結果]:

[總結]:

雖然是int型,能夠不返回,直接調用。不知道怎麼存儲maxCount:單獨加個變量就好了,何況加變量也不費事啊。

[複雜度]:Time complexity: O(n) Space complexity: O(n)

[算法思想:迭代/遞歸/分治/貪心]:

[關鍵模板化代碼]:

[其餘解法]:

[Follow Up]:

[LC給出的題目變變變]:

 [代碼風格] :

 [是否頭一次寫此類driver funcion的代碼] :

 [潛臺詞] :

 

class Solution {
    Map<Integer, Integer> sumToCount = new HashMap<>();
    int maxCount = 0;
    
    public int[] findFrequentTreeSum(TreeNode root) {
        //initilization: map, list res,[] result, maxCount
        List<Integer> res = new ArrayList<Integer>();
        
        postOrder(root);
        
        //if equals maxCount,add to list
        for (int sum : sumToCount.keySet()) {
            if (sumToCount.get(sum) == maxCount) {
                res.add(sum);
            }
        }

        //add to array
        int[] result = new int[res.size()];
        for (int i = 0; i < res.size(); i++) {
            result[i] = res.get(i);
        }
        
        //return
        return result;
    }
    
    public int postOrder(TreeNode root) {
        //corner case
        if (root == null) return 0;
        
        //traverse left and right
        int left = postOrder(root.left);
        int right = postOrder(root.right);
        int sum = left + right + root.val;
        
        //add sum to map
        sumToCount.put(sum, sumToCount.getOrDefault(sum, 0) + 1);
        int count = sumToCount.get(sum);
        //maintain maxCount
        maxCount = Math.max(maxCount, count);

        //return
        return sum;
    }
}
View Code
相關文章
相關標籤/搜索