Leetcode 508. Most Frequent Subtree Sum
题目链接: Most Frequent Subtree Sum
难度:Medium
题目大意:
给出二叉树,统计二叉树中所有子树的和的数量,返回数量最多的和。
思路:
参考高赞回答,利用递归来求二叉树中所有子树的和,用HashMap来统计次数。最后Integer的List通过for循环来转化成int类型的数组。
代码
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode() {}
* TreeNode(int val) { this.val = val; }
* TreeNode(int val, TreeNode left, TreeNode right) {
* this.val = val;
* this.left = left;
* this.right = right;
* }
* }
*/
class Solution {
Map<Integer,Integer> count=new HashMap<>();
int maxCount=0;
public int[] findFrequentTreeSum(TreeNode root) {
dfs(root);
List<Integer> list=new ArrayList();
for(Integer sum:count.keySet()){
if(count.get(sum)==maxCount){
list.add(sum);
}
}
int n=list.size();
int[] arr=new int[n];
for(int i=0;i<n;i++){
arr[i]=list.get(i);
}
return arr;
}
public int dfs(TreeNode root){
if(root==null){
return 0;
}
int left=dfs(root.left);
int right=dfs(root.right);
int sum=left+right+root.val;
count.put(sum,count.getOrDefault(sum,0)+1);
if(count.get(sum)>maxCount){
maxCount=count.get(sum);
}
return sum;
}
}