Average of Levels in Binary Tree
Posted amazingzoe
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了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 7 Output: [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.
1 /** 2 * Definition for a binary tree node. 3 * public class TreeNode { 4 * int val; 5 * TreeNode left; 6 * TreeNode right; 7 * TreeNode(int x) { val = x; } 8 * } 9 */ 10 public class Solution { 11 public List<Double> averageOfLevels(TreeNode root) { 12 List<Double> average = new ArrayList<>(); 13 if (root == null) return average; 14 15 Queue<TreeNode> queue = new LinkedList<>(); 16 queue.add(root); 17 while (queue.peek() != null) { 18 average.add(0.0); 19 int n = average.size() - 1; 20 21 int levelCount = queue.size(); 22 int m = levelCount; 23 while (levelCount-- != 0) { 24 TreeNode temp = queue.poll(); 25 average.set(n, average.get(n) + temp.val); 26 27 if (temp.left != null) queue.add(temp.left); 28 if (temp.right != null) queue.add(temp.right); 29 } 30 average.set(n, average.get(n) / m); 31 } 32 return average; 33 } 34 }
1 /** 2 * Definition for a binary tree node. 3 * public class TreeNode { 4 * int val; 5 * TreeNode left; 6 * TreeNode right; 7 * TreeNode(int x) { val = x; } 8 * } 9 */ 10 public class Solution { 11 public List<Double> averageOfLevels(TreeNode root) { 12 List<Double> sum = new ArrayList<Double>(); 13 List<Integer> count = new ArrayList<Integer>(); 14 15 levelTraversal(root, sum, count, 0); 16 countAverage(sum, count); 17 18 return sum; 19 } 20 21 private void levelTraversal(TreeNode root, List<Double> sum, List<Integer> count, int depth) { 22 if (root == null) return; 23 if (depth == sum.size()) { 24 sum.add(0.0); 25 count.add(0); 26 } 27 28 sum.set(depth, sum.get(depth) + root.val); 29 count.set(depth, count.get(depth) + 1); 30 31 levelTraversal(root.left, sum, count, depth + 1); 32 levelTraversal(root.right, sum, count, depth + 1); 33 } 34 35 private void countAverage(List<Double> sum, List<Integer> count) { 36 int n = sum.size(); 37 for (int i = 0; i < n; i++) { 38 sum.set(i, sum.get(i) * 1.0 / count.get(i)); 39 } 40 } 41 }
以上是关于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
637. Average of Levels in Binary Tree