LeetCode #637 Average of Levels in Binary Tree 二叉树的层平均值

Description:
Given a non-empty binary tree, return the average value of the nodes on each level in the form of an array.

Example:
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:

输入:

    3
   / \
  9  20
    /  \
   15   7

输出: [3, 14.5, 11]
解释:
第0层的平均值是 3, 第1层是 14.5, 第2层是 11. 因此返回 [3, 14.5, 11].

注意:

节点值的范围在32位有符号整数范围内。

思路:
参考LeetCode #107 Binary Tree Level Order Traversal II 二叉树的层次遍历 II
将每一层的结果记录求平均值即可
时间复杂度O(n), 空间复杂度O(n)

代码:
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 averageOfLevels(TreeNode* root) {
        vector result;
        queue q;
        q.push(root);
        while (q.size()) {
            double total = 0;
            int nums = q.size();
            for (int i = 0; i < nums; i++) {
                TreeNode* cur = q.front();
                q.pop();
                total += cur -> val;
                if (cur -> left) q.push(cur -> left);
                if (cur -> right) q.push(cur -> right);
            }
            result.push_back(total / nums);
        }
        return result;        
    }
};

Java:

/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
class Solution {
    public List averageOfLevels(TreeNode root) {
        List result = new ArrayList<>();
        Queue q = new LinkedList<>();
        q.offer(root);
        while (!q.isEmpty()) {
            double total = 0;
            int nums = q.size();
            for (int i = 0; i < nums; i++) {
                TreeNode cur = q.poll();
                total += cur.val;
                if (cur.left != null) q.offer(cur.left);
                if (cur.right != null) q.offer(cur.right);
            }
            result.add(total / nums);
        }
        return result;
    }
}

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: TreeNode) -> List[float]:
        queue, result = [root], []
        while queue:
            size, total = len(queue), 0
            for _ in range(size):
                item = queue.pop(0)
                total += item.val
                if item.left:
                    queue.append(item.left)
                if item.right:
                    queue.append(item.right)
            result.append(total / size)
        return result

你可能感兴趣的:(LeetCode #637 Average of Levels in Binary Tree 二叉树的层平均值)