637. 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.

取每层的平均值,则是层序遍历(BFS)

代码

public class AverageOfLevelsInBinaryTree {
    public static List averageOfLevels(TreeNode root) {
        List averageList = new ArrayList<>();
        List tmpList = new ArrayList<>();
        Queue queue = new LinkedList<>();
        if (root == null) {
            return null;
        }
        queue.add(root);
        while (!queue.isEmpty()) {
            long sum = 0;//注意得是long型,否则会溢出
            double avarage = 0;
            int n = queue.size();
            for (int i = 0; i < n; i++) {
                TreeNode currentNode = queue.peek();
                sum += currentNode.val;
                queue.poll();
                if (currentNode.left != null) {
                    queue.offer(currentNode.left);
                }
                if (currentNode.right != null) {
                    queue.offer(currentNode.right);
                }
            }
            avarage = (double)sum / n; 
            averageList.add(avarage);
        }
        return averageList;
    }

你可能感兴趣的:(637. Average of Levels in Binary Tree)