Java BFS concise solution


  • 0
    C
    public class Solution {
    public List<Double> averageOfLevels(TreeNode root) {
             Queue<TreeNode> queue=new LinkedList<>();
            List<Double> averageList=new ArrayList<>();
            if(root==null)
                return averageList;
            queue.offer(root);
            while (!queue.isEmpty())
            {
                int levelNum=queue.size();
                double sum=0;
                for (int i=0;i<levelNum;i++)
                {
                    if(queue.peek().left!=null)
                        queue.offer(queue.peek().left);
                    if(queue.peek().right!=null)
                        queue.offer(queue.peek().right);
                    sum=sum+queue.poll().val;
                }
                averageList.add(sum/levelNum);
            }
            return averageList;
            
        } 
    }
    

Log in to reply
 

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