其他分享
首页 > 其他分享> > 8.力扣-树-出现次数最多的子树元素和

8.力扣-树-出现次数最多的子树元素和

作者:互联网

力扣-树-出现次数最多的子树元素和

出现次数最多的子树元素和(LeetCode 508)

class Solution {
    private int maxcount=1;
    public int[] findFrequentTreeSum(TreeNode root) {
        if(root==null) {
            return new int[0];
        }
        Map<Integer,Integer> numcount=new HashMap<>();
        List<Integer> lst=new LinkedList<>();
        findTreeSum(root,numcount);
        Set Keys=numcount.keySet();
        for(Object k:Keys){         //遍历hashmap
            if(numcount.get(k)==maxcount) lst.add((int)k);
        }
        int[] ans=new int[lst.size()];
        for (int i = 0; i < lst.size(); i++) {
            ans[i]=lst.get(i);
        }
        return ans;
    }
    //第二三个函数可以合并为一个,详细做法见Solution1
    public void findTreeSum(TreeNode root,Map<Integer,Integer> count){
        if(root==null) return;
        if((count.getOrDefault(getSum(root),-1))==-1){
            count.put(getSum(root),1);
        }
        else{
            int value=count.get(getSum(root));
            count.put(getSum(root),value+1);
            if(value+1>maxcount) maxcount=value+1;
        }
        findTreeSum(root.left,count);
        findTreeSum(root.right,count);
    }
    public int getSum(TreeNode node){
        int sum=0;
        if(node==null){
            return 0;
        }
        sum+=node.val;
        sum+=getSum(node.left);
        sum+=getSum(node.right);
        return sum;
    }
}
class Solution1 {
    private int maxcount=1;//记录子树元素的最大重复个数
    public int[] findFrequentTreeSum(TreeNode root) {
        Map<Integer,Integer> hash=new HashMap<>();//记录子树元素和,以及出现的频数
        getSumAndCount(root,hash);
        int l=0;
        Set Keys=hash.keySet();
        List<Integer> list=new ArrayList<>();
        for(Object k:Keys){         //遍历hashmap
            if(hash.get(k)==maxcount) list.add((int)k);}
        int[] ans=new int[list.size()];
        while (l<list.size()) ans[l]=list.get(l++);
        return  ans;
    }
    private int getSumAndCount(TreeNode root, Map<Integer, Integer> map) {
        if (root == null) return 0;
        int l_sum = getSumAndCount(root.left, map);//求当前节点的左子树的"子树元素和"
        int r_sum = getSumAndCount(root.right, map);//求当前节点的右子树的"子树元素和"
        int ret = root.val + l_sum + r_sum;//该节点的子树元素和(也是返回值)
        if (map.containsKey(ret)) {//如果hashmap中包含这个"子树元素和"的值
            int temp = map.get(ret) + 1;
            map.put(ret, temp);//更新hashmap中的键值对
            if (maxcount < temp) maxcount = temp;//比较并更新“子树数元素和”的最大重复个数
        } else map.put(ret, 1);//如果不存在,直接存入即可
        return ret;
    }

}

标签:子树,int,sum,元素,力扣,次数,maxcount,root
来源: https://blog.csdn.net/caijizijiu/article/details/117673740