title: Average of each level in a Binary Tree
body: <p>I am trying to find the average of each level in a binary tree. I am doing BFS. I am trying to do it using a null node. Whenever I find a dummy node, that means I am at the last node at that level. The problem I am facing is that I am not able to add average of the last level in a tree using this. Can Someone Help me?</p>
  
  <p>Consider example [3,9,20,15,7]
  I am getting the output as [3.00000,14.50000]. Not getting the average of the last level that is 15 and 7
  Here's my code</p>
  
  <pre><code>/**
  * 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&lt;Double&gt; averageOfLevels(TreeNode root) {
      List&lt;Double&gt; list = new ArrayList&lt;Double&gt;();
      double sum = 0.0;
      Queue&lt;TreeNode&gt; q = new LinkedList&lt;TreeNode&gt;();
      TreeNode temp = new TreeNode(0);
      q.offer(root);
      q.offer(temp);
      int count = 0;
      while(!q.isEmpty()){
          root = q.poll();
          sum += root.val;
  
          if(root != temp)
          {
              count++;
              if(root.left != null){
                  q.offer(root.left);
              }
              if(root.right != null){
                  q.offer(root.right);
              }
          }
          else
          {
              if(!q.isEmpty()){
              list.add(sum / count);
              sum = 0;
              count = 0;
              q.add(temp);           
              }
        }
  
      }
      return list;
    }
  }
  </code></pre>