# 637.Average of Levels in Binary Tree

**637.Average of Levels in Binary Tree**

难度:Easy

> 给定一个非空二叉树, 返回一个由每层节点平均值组成的数组.

```
示例 1:

输入:
    3
   / \
  9  20
    /  \
   15   7
输出: [3, 14.5, 11]
解释:
第0层的平均值是 3,  第1层是 14.5, 第2层是 11. 因此返回 [3, 14.5, 11].
注意：

节点值的范围在32位有符号整数范围内。
```

分层遍历可以使用基本的队列存储，

```
/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
 * };
 */
class Solution {
public:
    vector<double> averageOfLevels(TreeNode* root) {
        vector<double>res;
        if(!root) return res;
        deque<TreeNode*> tree(1,root);
        while(!tree.empty())
        {
            double sum=0.0;
            int len=tree.size();
            int k=len;
            while(k--)
            {
                sum+=tree[0]->val;
                if(tree[0]->left) tree.push_back(tree[0]->left);
                if(tree[0]->right) tree.push_back(tree[0]->right);
                tree.pop_front();
            }
            res.push_back(sum/len);
            
        }
        return res;
        
    }
};
```


---

# Agent Instructions: Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://dfine.gitbook.io/leetcode/637.average_of_levels_in_binary_tree.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
