Average of Levels in Binary Tree

Return the average value at each depth of a binary tree.

Easy
Time O(n) Space O(n)
LeetCode
3 min read
tree bfs

Problem#

Return a list where the i-th entry is the average value of the nodes at depth i in a binary tree.

Examples#

  • [3,9,20,null,null,15,7][3.0, 14.5, 11.0].
  • [3,9,20,15,7][3.0, 14.5, 11.0].

Constraints#

  • 1 <= n <= 10^4, -2^31 <= Node.val <= 2^31 - 1.

Hints#

Hint
Size-snapshot BFS; sum then divide.

Approach#

BFS with the standard level-boundary trick. Accumulate sum into long long to avoid overflow with extreme Node.val near INT_MIN/INT_MAX.

Solution#

Average of Levels in Binary Tree
class Solution {
public:
vector<double> averageOfLevels(TreeNode* root) {
vector<double> ans;
queue<TreeNode*> q;
q.push(root);
while (!q.empty()) {
int sz = q.size();
long long sum = 0;
for (int i = 0; i < sz; ++i) {
TreeNode* cur = q.front(); q.pop();
sum += cur->val;
if (cur->left) q.push(cur->left);
if (cur->right) q.push(cur->right);
}
ans.push_back(static_cast<double>(sum) / sz);
}
return ans;
}
};

Editorial#

Standard BFS skeleton; the only non-trivial bit is overflow safety. Summing 10^4 values each near INT_MAX overflows int, so use long long. Cast to double last to preserve precision.

Complexity#

  • Time: O(n).
  • Space: O(width).

Concept revision#

Search ESC

Keyboard shortcuts

Shortcuts are disabled while typing in inputs.