Naive Java Solution with 2 lists with helper()


  • 2

    sumLs: store the sum of each level.
    cntLs: store each level node number.
    index in the list means level in the tree.

    public class Solution {
        public List<Double> averageOfLevels(TreeNode root) {
            List<Double> sumLs = new ArrayList<Double>();
            List<Integer> cntLs = new ArrayList<Integer>();
            if (root == null) return sumLs;
            helper(root, 0, sumLs, cntLs);
            for (int i = 0; i < sumLs.size(); i++)
                sumLs.set(i, sumLs.get(i) / cntLs.get(i));
            return sumLs;
        }
        
        private void helper(TreeNode root, int lv, List<Double> sumLs, List<Integer> cntLs) {
            if (root != null) {
            	if (sumLs.size() <= lv) {
            		sumLs.add((double) root.val);
            		cntLs.add(1);
            	} else {
            		sumLs.set(lv, sumLs.get(lv) + root.val);
            		cntLs.set(lv, cntLs.get(lv) + 1);
            	}
                helper(root.left, lv + 1, sumLs, cntLs);
                helper(root.right, lv + 1, sumLs, cntLs);
            }
        }
    }
    

Log in to reply
 

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