Concise DFS Java Solution using Hashmap


  • 0
    C
    int level = 0;
    public List<Double> averageOfLevels(TreeNode root) {
        List<Double> list = new ArrayList<Double>();
        HashMap<Integer, Integer> map = new HashMap<Integer, Integer>();
        getLevelSum(root, level, list, map);
        for(int i=0;i<list.size();i++){
            int count = map.get(i);
            list.set(i, list.get(i)/count);
        }        
        return list;
    }
    
    public void getLevelSum(TreeNode root, int level, List<Double> list, HashMap<Integer, Integer> map){
        if(root == null) return;
        if(level == list.size()){
            list.add((double)root.val);
            map.put(level, 1);
        }  
        else{
             list.set(level, list.get(level)+root.val);
             map.put(level, map.get(level)+1);
        } 
        getLevelSum(root.left, level+1, list, map);
        getLevelSum(root.right, level+1, list, map);
    }

Log in to reply
 

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