Java POST Order Tree Traversal + HashMaps


  • 0
    M
        public int[] findFrequentTreeSum(TreeNode root) {
            
            Map<Integer, Integer> mostFreqSums= new HashMap<Integer, Integer>();
            findFrequentTreeSumUtil(root, mostFreqSums);
            
            // Print all the subtree sums frequencies
            /*for (int k : mostFreqSums.keySet()) {
                System.out.println(k + " : " + mostFreqSums.get(k));
            }*/
            
            List<Integer> freqSums = new ArrayList<Integer>();
            
            for (int k : mostFreqSums.keySet()) {
                
                if (!freqSums.isEmpty()) {
                    if (mostFreqSums.get(freqSums.get(freqSums.size() - 1)) < mostFreqSums.get(k)) {
                        freqSums.clear();
                        freqSums.add(k);
                    } else if (mostFreqSums.get(freqSums.get(freqSums.size() - 1)) == mostFreqSums.get(k)) {
                        freqSums.add(k);
                    }
                } else {
                    freqSums.add(k);
                }
            }
            
            int idx = 0;
            int[] result = new int[freqSums.size()];
            for (int s : freqSums) {
                result[idx] = s;
                idx++;
            }
            
            return result;
            
        }
        
        public int findFrequentTreeSumUtil(TreeNode root, Map<Integer, Integer> mostFreqSums) {
            
            if (root == null) {
                return 0;
            }
            
            int leftSum = findFrequentTreeSumUtil(root.left, mostFreqSums);
            int rightSum = findFrequentTreeSumUtil(root.right, mostFreqSums);
            
            int sum = root.val + leftSum + rightSum;
            
            if (!mostFreqSums.containsKey(sum)) {
                mostFreqSums.put(sum, 0);
            }
            
            mostFreqSums.put(sum, mostFreqSums.get(sum) + 1);
            
            return sum;        
        }
    

Log in to reply
 

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