[LeetCode] 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:

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

二叉树的层平均值。给定一个非空二叉树, 返回一个由每层节点平均值组成的数组。

题意很简单,思路也类似102题,会用到BFS。直接给代码了。

时间O(n)

空间O(n)

Java实现

 1 /**
 2  * Definition for a binary tree node.
 3  * public class TreeNode {
 4  *     int val;
 5  *     TreeNode left;
 6  *     TreeNode right;
 7  *     TreeNode() {}
 8  *     TreeNode(int val) { this.val = val; }
 9  *     TreeNode(int val, TreeNode left, TreeNode right) {
10  *         this.val = val;
11  *         this.left = left;
12  *         this.right = right;
13  *     }
14  * }
15  */
16 class Solution {
17     public List averageOfLevels(TreeNode root) {
18         List res = new ArrayList<>();
19         // corner case
20         if (root == null) {
21             return res;
22         }
23 
24         // normal case
25         Queue queue = new LinkedList<>();
26         queue.offer(root);
27         while (!queue.isEmpty()) {
28             int size = queue.size();
29             double sum = 0.0;
30             for (int i = 0; i < size; i++) {
31                 TreeNode cur = queue.poll();
32                 sum += cur.val;
33                 if (cur.left != null) {
34                     queue.offer(cur.left);
35                 }
36                 if (cur.right != null) {
37                     queue.offer(cur.right);
38                 }
39             }
40             res.add(sum / size);
41         }
42         return res;
43     }
44 }

 

JavaScript实现

 1 /**
 2  * @param {TreeNode} root
 3  * @return {number[]}
 4  */
 5 var averageOfLevels = function (root) {
 6     let res = [];
 7     // corner case
 8     if (root == null) {
 9         return res;
10     }
11 
12     // normal case
13     let queue = [];
14     queue.push(root);
15     while (queue.length > 0) {
16         let size = queue.length;
17         let sum = 0.0;
18         for (let i = 0; i < size; i++) {
19             let cur = queue.shift();
20             sum += cur.val;
21             if (cur.left != null) {
22                 queue.push(cur.left);
23             }
24             if (cur.right != null) {
25                 queue.push(cur.right);
26             }
27         }
28         res.push(sum / size);
29     }
30     return res;
31 };

 

LeetCode 题目总结

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