508. Most Frequent Subtree Sum

来源:互联网 发布:淘宝怎么免单 编辑:程序博客网 时间:2024/05/22 06:49

题目

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.

解答

public class Solution {        HashMap<Integer,Integer> map = new HashMap<>();    int maxNum = 1;        public int[] findFrequentTreeSum(TreeNode root) {        if(root == null)            return new int[0];        treeSum(root);        ArrayList<Integer> list = new ArrayList<>();        for(Map.Entry<Integer,Integer> entry : map.entrySet()){            if(entry.getValue() == maxNum)                list.add(entry.getKey());        }        int[] res = new int[list.size()];        for(int i = 0; i < list.size(); i ++){            res[i] = list.get(i);        }        return res;    }        public int treeSum(TreeNode root){        int leftsum = (root.left == null) ? 0 : treeSum(root.left);        int rightsum = (root.right == null) ? 0 : treeSum(root.right);        int treeSum = root.val + leftsum + rightsum;        map.put(treeSum, map.getOrDefault(treeSum,0) + 1);        maxNum = Math.max(maxNum, map.get(treeSum));        return treeSum;     }}
算法思路:前序遍历,根、左子树、右子树,此根节点的和 = 根节点 + 左子树的和 + 右子树的和。就像求数组前n项的和一样,Sum(n) = Sum(n-1) + arr(n)。
代码分析:三目运算符优化代码;map.getOrDefault(key,val);


0 0
原创粉丝点击