<leetcode>637. Average of Levels in Binary Tree
来源:互联网 发布:中国人 知乎 编辑:程序博客网 时间:2024/06/04 19:35
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 7Output: [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.
题目大意:就是二叉树的同层级的结点的值的和求平均值
方法:一开始一直想着中序,左序,右序遍历,就想着拷贝一个相同的二叉树,想想很麻烦,就觉得应该是方法错误了。看了discuss的提示才想到BFS和DFS,,,看了二叉树都忘了、、这题BFS,存在队列里,就可以了
/** * Definition for a binary tree node. * public class TreeNode { * int val; * TreeNode left; * TreeNode right; * TreeNode(int x) { val = x; } * } */class Solution { public List<Double> averageOfLevels(TreeNode root) { List < Double > res = new ArrayList < > (); Queue < TreeNode > queue = new LinkedList < > (); queue.add(root); while (!queue.isEmpty()) { long sum = 0, count = 0; Queue < TreeNode > temp = new LinkedList < > (); while (!queue.isEmpty()) { TreeNode n = queue.remove(); sum += n.val; count++; if (n.left != null) temp.add(n.left); if (n.right != null) temp.add(n.right); } queue = temp; res.add((double)sum/ count); } return res; }}
阅读全文
0 0
- [Leetcode] Binary tree-- 637. Average of Levels in Binary Tree
- LeetCode average Of Levels in Binary Tree
- Average of Levels in Binary Tree(leetcode)
- LeetCode 637. Average of Levels in Binary Tree
- [LeetCode]637. Average of Levels in Binary Tree
- leetcode 637. Average of Levels in Binary Tree
- [LeetCode]637. Average of Levels in Binary Tree
- 【LeetCode】637. Average of Levels in Binary Tree
- leetcode 637. Average of Levels in Binary Tree
- leetcode 637. Average of Levels in Binary Tree
- [LeetCode] 637. Average of Levels in Binary Tree
- leetcode 637. Average of Levels in Binary Tree
- <leetcode>637. Average of Levels in Binary Tree
- LeetCode 637. Average of Levels in Binary Tree
- [LeetCode] 637.Average of Levels in Binary Tree
- 637. Average of Levels in Binary Tree
- 637. Average of Levels in Binary Tree
- 637. Average of Levels in Binary Tree
- 51nod 1050 循环数组最大子段和 !!!!巧妙
- (angularjs) 数据的增查(添加用户,查询名字,实现排序,判断非空 ,是否是数字,是否重名,敏感字符)
- 企业绩效(笔记)
- Pycharm2017更改主题
- 论文阅读:《Towards accurate multi-person pose estimation in the wild》CVPR 2017
- <leetcode>637. Average of Levels in Binary Tree
- 【nginx+tomcat】轻松搭建高性能负载均衡集群
- 07Python中的list数据类型
- SSl2267 2013年全国信息学分区联赛普级组day1 货车运输(rmq)
- GBK字符集和UTF8字符集的转换C++
- 08Python中的tupple数据类型
- Java锁示例
- JAVA学习笔记——Comparable 接口
- C语言学习-调用自定义函数