[LeetCode]637. Average of Levels in Binary Tree
来源:互联网 发布:读出文字的软件 编辑:程序博客网 时间:2024/06/07 02:48
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.
/** * Definition for a binary tree node. * public class TreeNode { * int val; * TreeNode left; * TreeNode right; * TreeNode(int x) { val = x; } * } */public class Solution {public List<Double> averageOfLevels(TreeNode root) { List<Double> list = new ArrayList<Double>(); Queue<TreeNode> que = new LinkedList<TreeNode>(); TreeNode temp=null; que.offer(root); int levelc, levelm, levelp; double curTot=0; levelm=levelp=1; levelc=0; while(!que.isEmpty()){ while(levelp>0){ temp = que.poll(); curTot+=temp.val; levelp--; if(temp.left!=null){que.offer(temp.left);levelc++;} if(temp.right!=null){que.offer(temp.right);levelc++;} } list.add((double)curTot/levelm); levelm=levelc; levelp=levelc; curTot=0; levelc=0; } return list; }}
坑:
一开始我设置curTot的类型为int,在输入值非常大(比如要进行2147483647+2147483647的运算时,结果数字会溢出int所能表示的范围)
所以在做题时要时刻注意防止溢出,选择合适的数据类型
阅读全文
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 1315 合法整数集
- git gitlab server install and configure
- std::this_thread::sleep_until
- Fzu上的重现赛
- Weave Scope
- [LeetCode]637. Average of Levels in Binary Tree
- TortoiseGit使用详解(一)
- BZOJ4033 [HAOI]树上染色
- PAT乙级 1009. 说反话 (20) 句子中单词逆序输出,'\0'的妙用,字符串分割
- 优先队列(C++/Java)
- Integer陷阱(0~127和其他 数值相等对象比较)
- Abstract
- MVC、MVVM和单向数据流的对比
- 剑指offer-左旋字符串