[LeetCode] 637. Average of Levels in Binary Tree 二叉树的层平均值
Given a non-empty binary tree, return the average value of the nodes on each level in the form of an array.
Example 1:
Input: 3 / \ 9 20 / \ 15 7 Output: [3, 14.5, 11] Explanation: The average value of nodes on level 0 is 3, on level 1 is 14.5, and on level 2 is 11. Hence return [3, 14.5, 11].
Note:
- The range of node's value is in the range of 32-bit signed integer.
给一个非空二叉树,返回每层的平均值组成的数组。
解法:BFS迭代,层序遍历,计算每层的平均值记录到res数组,最后返回res数组。
Java:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 | public List<Double> averageOfLevels(TreeNode root) { List<Double> result = new ArrayList<>(); Queue<TreeNode> q = new LinkedList<>(); if (root == null ) return result; q.add(root); while (!q.isEmpty()) { int n = q.size(); double sum = 0.0 ; for ( int i = 0 ; i < n; i++) { TreeNode node = q.poll(); sum += node.val; if (node.left != null ) q.offer(node.left); if (node.right != null ) q.offer(node.right); } result.add(sum / n); } return result; } |
Java: BFS
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 | public List<Double> averageOfLevels(TreeNode root) { List<Double> list = new LinkedList<>(); Queue<TreeNode> queue = new LinkedList<>(); queue.offer(root); while (!queue.isEmpty()) { int count = queue.size(); double sum = 0 ; for ( int i = 0 ; i < count; i++) { TreeNode cur = queue.poll(); sum += cur.val; if (cur.left != null ) queue.offer(cur.left); if (cur.right != null ) queue.offer(cur.right); } list.add(sum / count); } return list; } |
Java: DFS
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 | class Node { double sum; int count; Node ( double d, int c) { sum = d; count = c; } } public List<Double> averageOfLevels(TreeNode root) { List<Node> temp = new ArrayList<>(); helper(root, temp, 0 ); List<Double> result = new LinkedList<>(); for ( int i = 0 ; i < temp.size(); i++) { result.add(temp.get(i).sum / temp.get(i).count); } return result; } public void helper(TreeNode root, List<Node> temp, int level) { if (root == null ) return ; if (level == temp.size()) { Node node = new Node(( double )root.val, 1 ); temp.add(node); } else { temp.get(level).sum += root.val; temp.get(level).count++; } helper(root.left, temp, level + 1 ); helper(root.right, temp, level + 1 ); } |
Python:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 | # Time: O(n) # Space: O(h) class Solution( object ): def averageOfLevels( self , root): """ :type root: TreeNode :rtype: List[float] """ result = [] q = [root] while q: total, count = 0 , 0 next_q = [] for n in q: total + = n.val count + = 1 if n.left: next_q.append(n.left) if n.right: next_q.append(n.right) q = next_q result.append( float (total) / count) return result |
Python:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 | class Solution( object ): def averageOfLevels( self , root): """ :type root: TreeNode :rtype: List[float] """ if root is None : return [] result, current = [], [root] while current: next_level, vals, = [], 0.0 counts = len (current) for node in current: vals + = node.val if node.left: next_level.append(node.left) if node.right: next_level.append(node.right) current = next_level result.append(vals / counts) return result |
Python: wo
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 32 33 | # Definition for a binary tree node. # class TreeNode(object): # def __init__(self, x): # self.val = x # self.left = None # self.right = None class Solution( object ): def averageOfLevels( self , root): """ :type root: TreeNode :rtype: List[float] """ res = [] self .helper([root], res) return res def helper( self , q, res): sm = 0.0 counts = 0 next_level = [] while q: node = q.pop() counts + = 1 sm + = node.val if node.left: next_level.append(node.left) if node.right: next_level.append(node.right) res.append(sm / counts) if next_level: self .helper(next_level, res) |
C++:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 | class Solution { public : vector< double > averageOfLevels(TreeNode* root) { if (!root) return {}; vector< double > res; queue<TreeNode*> q{{root}}; while (!q.empty()) { int n = q.size(); double sum = 0; for ( int i = 0; i < n; ++i) { TreeNode *t = q.front(); q.pop(); sum += t->val; if (t->left) q.push(t->left); if (t->right) q.push(t->right); } res.push_back(sum / n); } return res; } }; |
C++:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 | class Solution { public : vector< double > averageOfLevels(TreeNode* root) { vector< double > res, cnt; helper(root, 0, cnt, res); for ( int i = 0; i < res.size(); ++i) { res[i] /= cnt[i]; } return res; } void helper(TreeNode* node, int level, vector< double >& cnt, vector< double >& res) { if (!node) return ; if (res.size() <= level) { res.push_back(0); cnt.push_back(0); } res[level] += node->val; ++cnt[level]; helper(node->left, level + 1, cnt, res); helper(node->right, level + 1, cnt, res); } }; |
类似题目:
[LeetCode] 102. Binary Tree Level Order Traversal 二叉树层序遍历
[LeetCode] 107. Binary Tree Level Order Traversal II 二叉树层序遍历 II
[LeetCode] 199. Binary Tree Right Side View 二叉树的右侧视图
All LeetCode Questions List 题目汇总
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· AI与.NET技术实操系列:向量存储与相似性搜索在 .NET 中的实现
· 基于Microsoft.Extensions.AI核心库实现RAG应用
· Linux系列:如何用heaptrack跟踪.NET程序的非托管内存泄露
· 开发者必知的日志记录最佳实践
· SQL Server 2025 AI相关能力初探
· 震惊!C++程序真的从main开始吗?99%的程序员都答错了
· 【硬核科普】Trae如何「偷看」你的代码?零基础破解AI编程运行原理
· 单元测试从入门到精通
· winform 绘制太阳,地球,月球 运作规律
· 上周热点回顾(3.3-3.9)