bfs O(n) time O(logn) space
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31
|
class Solution { public: vector<double> averageOfLevels(TreeNode* root) { if (!root) return {}; vector<double> res; queue<TreeNode *> q; q.push(root); while (!q.empty()) { int n = q.size(); double sum = 0; for (int i = 0; i < n; ++i) { auto 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 / n); } return res; } };
|