File tree 2 files changed +60
-0
lines changed
2 files changed +60
-0
lines changed Original file line number Diff line number Diff line change 72
72
| 509| [ 斐波那契数] ( https://leetcode.cn/problems/fibonacci-number/ ) | [ JavaScript] ( ./algorithms/fibonacci-number.js ) | Easy|
73
73
| 543| [ 二叉树的直径] ( https://leetcode.cn/problems/diameter-of-binary-tree/ ) | [ JavaScript] ( ./algorithms/diameter-of-binary-tree.js ) | Easy|
74
74
| 617| [ 合并二叉树] ( https://leetcode.cn/problems/merge-two-binary-trees/ ) | [ JavaScript] ( ./algorithms/merge-two-binary-trees.js ) | Easy|
75
+ | 637| [ 二叉树的层平均值] ( https://leetcode.cn/problems/average-of-levels-in-binary-tree/ ) | [ JavaScript] ( ./algorithms/average-of-levels-in-binary-tree.js ) | Easy|
75
76
| 687| [ 最长同值路径] ( https://leetcode.cn/problems/longest-univalue-path/ ) | [ JavaScript] ( ./algorithms/longest-univalue-path.js ) | Medium|
76
77
| 700| [ 二叉搜索树中的搜索] ( https://leetcode.cn/problems/search-in-a-binary-search-tree/ ) | [ JavaScript] ( ./algorithms/search-in-a-binary-search-tree.js ) | Easy|
77
78
| 704| [ 二分查找] ( https://leetcode.cn/problems/binary-search/ ) | [ JavaScript] ( ./algorithms/binary-search.js ) | Easy|
Original file line number Diff line number Diff line change
1
+ /**
2
+ * Definition for a binary tree node.
3
+ * function TreeNode(val, left, right) {
4
+ * this.val = (val===undefined ? 0 : val)
5
+ * this.left = (left===undefined ? null : left)
6
+ * this.right = (right===undefined ? null : right)
7
+ * }
8
+ */
9
+ /**
10
+ * 二叉树的层平均值
11
+ * @param {TreeNode } root
12
+ * @return {number[] }
13
+ */
14
+ var averageOfLevels = function ( root ) {
15
+ // 1. DFS
16
+ let result = [ ] ;
17
+ const dfs = ( node , level = 0 ) => {
18
+ if ( node ) {
19
+ if ( ! result [ level ] ) result [ level ] = [ ] ;
20
+ result [ level ] . push ( node . val ) ;
21
+ dfs ( node . left , level + 1 ) ;
22
+ dfs ( node . right , level + 1 ) ;
23
+ }
24
+ } ;
25
+ dfs ( root ) ;
26
+
27
+ result = result . map ( ( item ) => {
28
+ const sum = item . reduce ( ( a , b ) => a + b ) ;
29
+ return Number ( ( sum / item . length ) . toFixed ( 5 ) ) ;
30
+ } ) ;
31
+
32
+ return result ;
33
+
34
+ // 2. BFS
35
+ // return bfs(root);
36
+ } ;
37
+
38
+ function bfs ( root ) {
39
+ const result = [ ] ;
40
+ const queue = [ ] ;
41
+ queue . push ( root ) ;
42
+
43
+ while ( queue . length > 0 ) {
44
+ const len = queue . length ;
45
+ let size = len ;
46
+ let sum = 0 ;
47
+
48
+ while ( size -- ) {
49
+ const node = queue . shift ( ) ;
50
+ sum += node . val ;
51
+ node . left && queue . push ( node . left ) ;
52
+ node . right && queue . push ( node . right ) ;
53
+ }
54
+
55
+ result . push ( Number ( ( sum / len ) . toFixed ( 5 ) ) ) ;
56
+ }
57
+
58
+ return result ;
59
+ }
You can’t perform that action at this time.
0 commit comments