File tree 2 files changed +42
-0
lines changed
2 files changed +42
-0
lines changed Original file line number Diff line number Diff line change 419
419
617|[ Merge Two Binary Trees] ( ./0617-merge-two-binary-trees.js ) |Easy|
420
420
621|[ Task Scheduler] ( ./0621-task-scheduler.js ) |Medium|
421
421
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|
422
423
643|[ Maximum Average Subarray I] ( ./0643-maximum-average-subarray-i.js ) |Easy|
423
424
645|[ Set Mismatch] ( ./0645-set-mismatch.js ) |Medium|
424
425
648|[ Replace Words] ( ./0648-replace-words.js ) |Medium|
Original file line number Diff line number Diff line change
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
+ } ;
You can’t perform that action at this time.
0 commit comments