問題:
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:
image.pngreturn [2, -3, 4], since all the values happen only once, return all of them in any order.
Examples 2
Input:
image.pngreturn [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.
大意:
給出一個樹的根節點,要求你找到出現最頻繁的子樹和。一個節點的子樹和是指其所有子節點以及子節點的子節點的值之和(包含節點本身)。所以最頻繁的子樹和是什么?如果有并列的,返回所有最高頻率的值,順序不限。
例1:
輸入:
image.png
返回 [2, -3, 4],因為所有值都只出現了一次,以任意順序返回它們。
例2:
輸入:
image.png
返回 [2],因為2這個和出現了兩次,而 -5 只出現了一次。
注意:你可以假設所有子樹的和都在32位int型范圍內。
思路:
要計算一個節點的子樹和其實不難,只需要用遞歸不斷判斷其子節點有沒有左右子節點,有的話就加起來其值就好了。
但是這道題要比較所有節點的子樹和,那就要求每遇到一個節點,都要以這個節點為根節點,計算其子樹和,所以每次遞歸時都要計算新計算一次。
那怎么記錄所有子樹和呢?這道題既然是要求找出出現頻率最高的子樹和值,那肯定要記錄各個值出現的次數,方法也就呼之欲出了,用HashMap,以子樹和為key,以出現次數為value,對于已經出現過的子樹和,就將其value+1,沒出現過的就添加到HashMap中去,其value設為1。這樣就可以邊計算所有子樹和,邊記錄各個和出現的次數了。
現在只剩下一個問題,找到出現最頻繁的子樹和,而且不一定只有一個子樹和值。所以我們要遍歷HashMap,記錄出現的次數最大的子樹和,因為可能有多個,我們用數組來記錄,如果碰到次數更當前記錄的次數最大的一直的子樹和,就添加到數組中,當出現更大次數的時候就重新記錄,替代數組第一個元素,同時用一個int型變量num來記錄最大出現頻率下有幾個子樹和,可以保證遍歷HashMap完后前num個數組元素是要的結果,我們取這幾個就可以了。
這個做法已經算快的了,打敗了91%。
代碼(Java):
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
public class Solution {
public int[] findFrequentTreeSum(TreeNode root) {
if (root == null) return new int[0];
HashMap<Integer, Integer> map = new HashMap<Integer, Integer>();
countSum(root, map);
int[] all = new int[map.size()];
int num = 0;
int big = 0;
Iterator iter = map.entrySet().iterator();
while (iter.hasNext()) {
Map.Entry entry = (Map.Entry)iter.next();
if ((int)entry.getValue() > big) {
all[0] = (int)entry.getKey();
num = 1;
big = (int)entry.getValue();
} else if ((int)entry.getValue() == big) {
all[num] = (int)entry.getKey();
num++;
}
}
return Arrays.copyOfRange(all, 0, num);
}
public int countSum(TreeNode root, HashMap<Integer, Integer> map) {
int sum = 0;
sum += root.val;
if (root.left != null) sum += countSum(root.left, map);
if (root.right != null) sum += countSum(root.right, map);
if (map.get(sum) != null) {// 之前放過
map.put(sum, map.get(sum)+1);
} else {
map.put(sum, 1);
}
return sum;
}
}
合集:https://github.com/Cloudox/LeetCode-Record