Java accepted solution


  • 0
    M
    import java.util.Map.Entry;
    public class Solution {
        public int[] findFrequentTreeSum(TreeNode root) {
    		
        	if(root==null)
        		return new int[]{};
        	
        	List<Integer> res = new ArrayList<>();
    
        	//find all sum values
        	findsum(root,res);
        	
            //put them in dict
        	HashMap<Integer, Integer> rest = new HashMap<>();
        	
        	for(int i=0; i<res.size();i++){
        		if(rest.containsKey(res.get(i))){
        			rest.put(res.get(i), rest.get(res.get(i))+1);
        		}
        		else
        			rest.put(res.get(i), +1);
        	}
        	
            
        	//sort by value in reverse order
        	Map<Integer, Integer> sortedMap = 
        		     rest.entrySet().stream()
        		    .sorted(Entry.comparingByValue(Comparator.reverseOrder()))
        		    .collect(Collectors.toMap(Entry::getKey, Entry::getValue,
        		                              (e1, e2) -> e1, LinkedHashMap::new));
        	
        	
        	List<Integer> tempr = new ArrayList<>();
        	
        	int count=0;
        	int i=0;
        	int max=0;
        	for(Map.Entry<Integer,Integer> entry: sortedMap.entrySet()){
    
        		if(count==0){
        			tempr.add(entry.getKey());
        			max = entry.getValue();
        			i++;
        			count++;
        		}
        		else if(entry.getValue()==max){
        			tempr.add(entry.getKey());
        			i++;
        		}
        		else
        			break;
        	}
        	
        	int[] resf = new int[tempr.size()];
        	
        	for(int k=0; k<tempr.size(); k++){
        		resf[k] = tempr.get(k);
        	}
        	
        	return resf;
            
        
        }
        
        public static int findsum(TreeNode root, List<Integer> res) {
    		// TODO Auto-generated method stub
    		if(root==null){
    			return 0;
    		}
    		
    		int left_sum = findsum(root.left,res);
    		int right_sum = findsum(root.right,res);
    		int mysum = root.val + left_sum + right_sum;
    		res.add(mysum);
    		return mysum;
    	}
    }
    

Log in to reply
 

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