637. Average of Levels in Binary Tree

637. Average of Levels in Binary Tree

/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
class Solution {
    public List averageOfLevels(TreeNode root) {
       List out = new ArrayList();
        Queue q = new LinkedList();
        q.add(root);
        
        while(! q.isEmpty()){
            int len = q.size();
            Double sum = 0.0;
            for (int i = 0; i < len; i++){
               TreeNode c = q.remove();
                if (c != null){
               sum += c.val; 
                if(c.left !=null)q.add(c.left);
                if(c.right != null)q.add(c.right);
                }

            }
                          out.add(sum/len);

        }
      return out;  
    }
}

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s