Simple Java 100 % AC Solution


  • 0
    public List<Double> averageOfLevels(TreeNode root) {
        List<long []> list = new ArrayList<>();
        helper (root, list, 1);
    
        List<Double> ans = new ArrayList<>();
        for (long [] info : list) ans.add (info [0] * 1d/info [1]);
        return ans;
    }
        
    private void helper (TreeNode node, List<long[]> list, int level) {
        if (node == null) return;
        if (list.size () < level) list.add (new long [] { 0, 0 });
        list.get (level - 1) [0] += node.val; 
        list.get (level - 1) [1] ++;
    
        helper (node.left, list, level + 1);
        helper (node.right, list, level + 1);
    }
    

Log in to reply
 

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