share my java solution!


  • 0
    T
    /**
     * Definition for a binary tree node.
     * public class TreeNode {
     *     int val;
     *     TreeNode left;
     *     TreeNode right;
     *     TreeNode(int x) { val = x; }
     * }
     */
    public class Solution {
        public List<Double> averageOfLevels(TreeNode root) {
            List<Double> res=new ArrayList<>();
            if(root==null) return res;
            
            Queue<TreeNode> queue=new LinkedList<>();
            queue.offer(root);
            while(!queue.isEmpty()){
                int size=queue.size();
                double sum=0;
                int len=size;
                while(size--!=0){
                   TreeNode t=queue.poll();
                   sum+=t.val;
                   if(t.left!=null){
                       queue.offer(t.left);
                   }
                    if(t.right!=null){
                        queue.offer(t.right);
                    }
                }
                res.add(sum/(double)len);
            }
            
            return res;
        }
    }
    
    

Log in to reply
 

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