JAVA simple recursive solution


  • 0
    V
    /**
     * Definition for a binary tree node.
     * public class TreeNode {
     *     int val;
     *     TreeNode left;
     *     TreeNode right;
     *     TreeNode(int x) { val = x; }
     * }
     */
    
    class Pair {
        double val;
        long count;
        Pair(double v, long c) {
            val = v;
            count = c;
        }
    }
    
    public class Solution {
        List<Pair> counts;
        public List<Double> averageOfLevels(TreeNode root) {
            List<Double> avg = new ArrayList<>();
            if(root == null) return avg;
            counts = new ArrayList<>();
            traverseLevels(root, 0);
            for(Pair p: counts) {
                double a = p.val / (double)p.count;
                avg.add(a);
            }
            return avg;
        }
        
        private void traverseLevels(TreeNode n, int level) {
            if(n == null) return;
            if(counts.size() <= level) counts.add(new Pair(0,0));
            Pair p = counts.get(level);
            counts.get(level).val = p.val + n.val;
            counts.get(level).count = p.count + 1;
            traverseLevels(n.left, level+1);
            traverseLevels(n.right, level+1);
        }
    }
    

Log in to reply
 

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