637. 二叉树的层平均值
题目:
思路:
【1】这道题需要知道层次遍历这个理念,因为层次遍历就是把树的节点按照层级来输出,那么既然一层的数据都有了,对这一层进行平均数的统计也就简单了。
代码展示:
//时间4 ms 击败 8.92% //内存43.4 MB 击败40.98% //基于层次遍历来进行变动 /** * Definition for a binary tree node. * public class TreeNode { * int val; * TreeNode left; * TreeNode right; * TreeNode() {} * TreeNode(int val) { this.val = val; } * TreeNode(int val, TreeNode left, TreeNode right) { * this.val = val; * this.left = left; * this.right = right; * } * } */ class Solution { public List<Double> averageOfLevels(TreeNode root) { List<Double> res = new ArrayList<Double>(); if (root == null) return res; Queue<TreeNode> que = new LinkedList<>(); que.add(root); int count = que.size(); TreeNode temp; while (!que.isEmpty()){ List<Integer> resList = new ArrayList<>(); while (count > 0){ temp = que.poll(); resList.add(temp.val); if (temp.left != null) que.add(temp.left); if (temp.right != null) que.add(temp.right); count--; } double sum = 0; for (int tem : resList){ sum += tem; } res.add(sum/resList.size()); count = que.size(); } return res; } } //再简化一下一些不必要的操作 //时间2 ms 击败 92.18% //内存43.5 MB 击败 22.17% /** * Definition for a binary tree node. * public class TreeNode { * int val; * TreeNode left; * TreeNode right; * TreeNode() {} * TreeNode(int val) { this.val = val; } * TreeNode(int val, TreeNode left, TreeNode right) { * this.val = val; * this.left = left; * this.right = right; * } * } */ class Solution { public List<Double> averageOfLevels(TreeNode root) { List<Double> res = new ArrayList<Double>(); if (root == null) return res; Queue<TreeNode> que = new LinkedList<>(); que.add(root); int count = que.size(); TreeNode temp; while (!que.isEmpty()){ int size = que.size(); double sum = 0; while (count > 0){ temp = que.poll(); sum += temp.val; if (temp.left != null) que.add(temp.left); if (temp.right != null) que.add(temp.right); count--; } res.add(sum/size); count = que.size(); } return res; } }