138、二叉樹的層平均值
阿新 • • 發佈:2018-12-31
題目描述
比較簡單的一道題目,需要注意的是要將sum的型別改成long這樣就不會溢位了,否則測試用例會出現-1這個bug:
/** * 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> list = new ArrayList<>(); Deque<TreeNode> tem = new LinkedList<>(); tem.offer(root); while (!tem.isEmpty()) { int size = tem.size(); long sum = 0; for (int i = 0; i < size; i++) { TreeNode node = tem.poll(); sum+=node.val; if(node.left != null){ tem.offer(node.left); } if(node.right != null){ tem.offer(node.right); } } list.add((double)sum/size); } return list; } }