Average of Levels in Binary Tree
Return the average value at each depth of a binary tree.
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#
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; }};func averageOfLevels(root *TreeNode) []float64 { ans := []float64{} q := []*TreeNode{root} for len(q) > 0 { sz := len(q) var sum int64 = 0 for i := 0; i < sz; i++ { cur := q[i] sum += int64(cur.Val) if cur.Left != nil { q = append(q, cur.Left) } if cur.Right != nil { q = append(q, cur.Right) } } q = q[sz:] ans = append(ans, float64(sum)/float64(sz)) } return ans}from collections import dequefrom typing import List, Optional
class Solution: def averageOfLevels(self, root: Optional[TreeNode]) -> List[float]: ans: List[float] = [] q = deque([root]) while q: sz = len(q) total = 0 for _ in range(sz): cur = q.popleft() total += cur.val if cur.left: q.append(cur.left) if cur.right: q.append(cur.right) ans.append(total / sz) return ansvar averageOfLevels = function(root) { const ans = []; let q = [root]; while (q.length > 0) { const sz = q.length; let sum = 0; const next = []; for (let i = 0; i < sz; i++) { const cur = q[i]; sum += cur.val; if (cur.left) next.push(cur.left); if (cur.right) next.push(cur.right); } ans.push(sum / sz); q = next; } return ans;};class Solution { public List<Double> averageOfLevels(TreeNode root) { List<Double> ans = new ArrayList<>(); Deque<TreeNode> q = new ArrayDeque<>(); q.offer(root); while (!q.isEmpty()) { int sz = q.size(); long sum = 0; for (int i = 0; i < sz; i++) { TreeNode cur = q.poll(); sum += cur.val; if (cur.left != null) q.offer(cur.left); if (cur.right != null) q.offer(cur.right); } ans.add((double) sum / sz); } return ans; }}function averageOfLevels(root: TreeNode | null): number[] { const ans: number[] = []; let q: TreeNode[] = root ? [root] : []; while (q.length > 0) { const sz = q.length; let sum = 0; const next: TreeNode[] = []; for (let i = 0; i < sz; i++) { const cur = q[i]; sum += cur.val; if (cur.left) next.push(cur.left); if (cur.right) next.push(cur.right); } ans.push(sum / sz); q = next; } 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#
Related#