题目描述

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:

  1. The range of node's value is in the range of 32-bit signed integer.

解法一

思路

这题是典型的BFS了,只需要在遍历当前层级的时候记录下结点个数和值的累加和就好了。

Python

# Definition for a binary tree node.
# class TreeNode:
#     def __init__(self, x):
#         self.val = x
#         self.left = None
#         self.right = None


class Solution:
    def averageOfLevels(self, root):
        """
        :type root: TreeNode
        :rtype: List[float]
        """
        if root is None:
            return []
        queue = collections.deque()
        result = []
        queue.append(root)
        while queue:
            sum_current_level = 0
            count_current_level = len(queue)
            for _ in range(count_current_level):
                current = queue.popleft()
                sum_current_level += current.val
                if current.left:
                    queue.append(current.left)
                if current.right:
                    queue.append(current.right)
            if count_current_level != 0:
                result.append(sum_current_level / count_current_level)
        return result

Java

/**
 * 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) {
        if (root == null) {
            return new ArrayList<>();
        }
        Queue<TreeNode> queue = new ArrayDeque<>();
        List<Double> result = new ArrayList<>();
        queue.add(root);
        while (!queue.isEmpty()) {
            long sumCurrentLevel = 0;
            int countCurrentLevel = queue.size();
            for (int i = 0; i < countCurrentLevel; i++) {
                TreeNode current = queue.poll();
                sumCurrentLevel += current.val;
                if (current.left != null) {
                    queue.add(current.left);
                }
                if (current.right != null) {
                    queue.add(current.right);
                }
            }
            if (countCurrentLevel != 0) {
                result.add((double) sumCurrentLevel / countCurrentLevel);
            }
        }
        return result;
    }
}

C++

/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
 * };
 */
class Solution {
public:
    vector<double> averageOfLevels(TreeNode *root) {
        if (root == nullptr) {
            return vector<double>();
        }
        queue<TreeNode *> que;
        vector<double> result;
        que.push(root);
        while (!que.empty()) {
            long sumCurrentLevel = 0;
            int countCurrentLevel = que.size();
            for (int i = 0; i < countCurrentLevel; i++) {
                TreeNode *current = que.front();
                que.pop();
                sumCurrentLevel += current->val;
                if (current->left != nullptr) {
                    que.push(current->left);
                }
                if (current->right != nullptr) {
                    que.push(current->right);
                }
            }
            if (countCurrentLevel != 0) {
                result.push_back((double) sumCurrentLevel / countCurrentLevel);
            }
        }
        return result;
    }
};