# [637\. Average of Levels in Binary Tree](https://leetcode.com/problems/average-of-levels-in-binary-tree/) :::spoiler Solution ```cpp= /** * Definition for a binary tree node. * struct TreeNode { * int val; * TreeNode *left; * TreeNode *right; * TreeNode() : val(0), left(nullptr), right(nullptr) {} * TreeNode(int x) : val(x), left(nullptr), right(nullptr) {} * TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {} * }; */ #define ll long long class Solution { public: vector<double> averageOfLevels(TreeNode* root) { vector<double> res; queue<TreeNode*> q{{root}}; while (!q.empty()) { int qSize = q.size(); double sum = 0; for (int i = 0; i < qSize; ++i) { TreeNode* node = q.front(); q.pop(); sum += node->val; if (node->left) q.push(node->left); if (node->right) q.push(node->right); } res.push_back(sum / qSize); } return res; } }; ``` - 時間複雜度:$O(n)$ - 空間複雜度:$O(m)$ :::
×
Sign in
Email
Password
Forgot password
or
By clicking below, you agree to our
terms of service
.
Sign in via Facebook
Sign in via Twitter
Sign in via GitHub
Sign in via Dropbox
Sign in with Wallet
Wallet (
)
Connect another wallet
New to HackMD?
Sign up