Easy java solution with hashMap


  • 1
    T

    Simply traversing the tree and writing levels as key,and the value is a sum of values at that level.

    public class Solution {
        HashMap<Integer,Double> hashMap = new HashMap<>();
        HashMap<Integer,Integer> aMap = new HashMap<>();
        public List<Double> averageOfLevels(TreeNode root) {
            addToHash(root,0);
            List<Double> list = new ArrayList<>();
            for(int i =0;hashMap.containsKey(i);++i){
                list.add(hashMap.get(i)/aMap.get(i));
            }
            return list;
            
        }
        public void addToHash(TreeNode root,int level){
            if(root == null){
                return;
            }
            hashMap.put(level,(root.val + (hashMap.containsKey(level)?hashMap.get(level):0)));
            aMap.put(level,(aMap.containsKey(level)?aMap.get(level):0) + 1);
            addToHash(root.left,level+1);
            addToHash(root.right,level+1);
        }
    }
    

Log in to reply
 

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