Leetcode 637. Average of Levels in Binary Tree
You are given the root of a binary tree. Your task is to find the average value of the nodes on each level in the tree. Return the averages as an array of floating-point numbers.
Before we proceed to the strategy and coding part, let’s clarify a few things:
#include <vector>
#include <queue>
#include <cmath>
using namespace std;
// 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) {}
};
class Solution {
public:
vector<double> averageOfLevels(TreeNode* root) {
if (!root) return {};
vector<double> result;
queue<TreeNode*> q;
q.push(root);
while (!q.empty()) {
int size = q.size();
long sum = 0; // Using long to handle larger sums without overflow
for (int i = 0; i < size; ++i) {
TreeNode* node = q.front();
q.pop();
sum += node->val;
if (node->left) q.push(node->left);
if (node->right) q.push(node->right);
}
result.push_back(static_cast<double>(sum) / size);
}
return result;
}
};
Got blindsided by a question you didn’t expect?
Spend too much time studying?
Or simply don’t have the time to go over all 3000 questions?