Fast clean Java AC solution beats 100%


  • 0
    W
        public List<Double> averageOfLevels(TreeNode root) {
            List<Double> res = new ArrayList<>();
            if (root == null) return res;
            Queue<TreeNode> q1 = new LinkedList<>();
            Queue<TreeNode> q2 = new LinkedList<>();
            q1.offer(root);
            while (!q1.isEmpty()) {
                long sum = 0;
                long size = 0;
                while (!q1.isEmpty()) {
                    TreeNode node = q1.poll();
                    size++;
                    sum += node.val;
                    if (node.left != null) q2.offer(node.left);
                    if (node.right != null) q2.offer(node.right);
                }
                res.add((double) sum / (double) size);
                Queue<TreeNode> tmp = q1;
                q1 = q2;
                q2 = tmp;
            }
            return res;
        }
    

Log in to reply
 

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