Java Solution use post-order beat 98%


  • 0
    L
    public class Solution {
        private Map<Integer,Integer> map = new HashMap<>();
        private int max = 0;
        private List<Integer> sum = new ArrayList<>();
        
        private void cal(TreeNode root){
            if(root!=null){
                cal(root.left);
                cal(root.right);
                root.val += (root.left==null?0:root.left.val) + (root.right==null?0:root.right.val);
                int freq = map.getOrDefault(root.val, 0) + 1;
                map.put(root.val, freq);
                if(freq>max){
                    max = freq;
                    sum.clear();
                    sum.add(root.val);
                }else if(freq==max){
                    sum.add(root.val);
                }
            }
        }
        public int[] findFrequentTreeSum(TreeNode root) {
            cal(root);
            int[] res = new int[sum.size()];
            for(int i=0;i<res.length;i++){
                res[i] = sum.get(i);
            }
            return res;
        }
    }
    

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.