list.clear() vs list = new ArrayList<>(); ?


  • 0
    D

    I am using an arraylist to store the sum values and populate it if the frequency of the sum is equal to the max seen so far. If the frequency is higher than the current max, I allocate the arraylist to new ArrayList<>(); (line 31 in the code).
    However, I get incorrect answer if I allocate a new ArrayList.
    But the code works if I clear the list.
    I am having hard time figuring out why would new ArrayList<>() not work and list.clear() would??

    '''
    public class Solution {
    int max = -1;
    public int[] findFrequentTreeSum(TreeNode root) {

        Map<Integer, Integer> map = new HashMap<>();
        List<Integer> maxFrequency = new ArrayList<>();
        
        computeFrequency(root, map, maxFrequency);
        
        int[] result = new int[maxFrequency.size()];
        
        for(int i = 0; i < maxFrequency.size(); i++)
            result[i] = maxFrequency.get(i);
        
        return result;
    }
    
    /* post-order traversal */
    private int computeFrequency(TreeNode root, Map<Integer, Integer> map, List<Integer> maxFrequency){
        if(root == null)
            return 0;
        
        int sumLeft = computeFrequency(root.left, map, maxFrequency);
        int sumRight = computeFrequency(root.right, map, maxFrequency);
        int sum = root.val + sumLeft + sumRight;
        
        int frequency = map.getOrDefault(sum, 0) + 1;
    	map.put(sum, frequency);
        
        if(frequency > max){
            maxFrequency.clear();   /* maxFrequency = new ArrayList<>(); */
            maxFrequency.add(sum);
            max = frequency;
        }
    
        else if(frequency == max)
            maxFrequency.add(sum);
        
        return sum;
    }
    

    }
    '''


Log in to reply
 

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