Skip to content

Commit b0faae9

Browse files
committed
Add solution #637
1 parent b48a4f2 commit b0faae9

File tree

2 files changed

+42
-0
lines changed

2 files changed

+42
-0
lines changed

README.md

+1
Original file line numberDiff line numberDiff line change
@@ -419,6 +419,7 @@
419419
617|[Merge Two Binary Trees](./0617-merge-two-binary-trees.js)|Easy|
420420
621|[Task Scheduler](./0621-task-scheduler.js)|Medium|
421421
628|[Maximum Product of Three Numbers](./0628-maximum-product-of-three-numbers.js)|Easy|
422+
637|[Average of Levels in Binary Tree](./0637-average-of-levels-in-binary-tree.js)|Easy|
422423
643|[Maximum Average Subarray I](./0643-maximum-average-subarray-i.js)|Easy|
423424
645|[Set Mismatch](./0645-set-mismatch.js)|Medium|
424425
648|[Replace Words](./0648-replace-words.js)|Medium|
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,41 @@
1+
/**
2+
* 637. Average of Levels in Binary Tree
3+
* https://leetcode.com/problems/average-of-levels-in-binary-tree/
4+
* Difficulty: Easy
5+
*
6+
* Given the root of a binary tree, return the average value of the nodes on each level in the
7+
* form of an array. Answers within 10-5 of the actual answer will be accepted.
8+
*/
9+
10+
/**
11+
* Definition for a binary tree node.
12+
* function TreeNode(val, left, right) {
13+
* this.val = (val===undefined ? 0 : val)
14+
* this.left = (left===undefined ? null : left)
15+
* this.right = (right===undefined ? null : right)
16+
* }
17+
*/
18+
/**
19+
* @param {TreeNode} root
20+
* @return {number[]}
21+
*/
22+
var averageOfLevels = function(root) {
23+
const result = [];
24+
const queue = [root];
25+
26+
while (queue.length) {
27+
const level = queue.length;
28+
let sum = 0;
29+
30+
for (let i = 0; i < level; i++) {
31+
const node = queue.shift();
32+
sum += node.val;
33+
if (node.left) queue.push(node.left);
34+
if (node.right) queue.push(node.right);
35+
}
36+
37+
result.push(sum / level);
38+
}
39+
40+
return result;
41+
};

0 commit comments

Comments
 (0)