[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:

  1. 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所能表示的范围

所以在做题时要时刻注意防止溢出,选择合适的数据类型