Skip to content

Commit f46367c

Browse files
authored
feat: update solutions to lc problem: No.637 (doocs#3122)
No.0637.Average of Levels in Binary Tree
1 parent b585fb1 commit f46367c

File tree

6 files changed

+120
-102
lines changed

6 files changed

+120
-102
lines changed

solution/0600-0699/0637.Average of Levels in Binary Tree/README.md

+44-34
Original file line numberDiff line numberDiff line change
@@ -62,6 +62,12 @@ tags:
6262

6363
### 方法一:BFS
6464

65+
我们可以使用广度优先搜索的方法,遍历每一层的节点,计算每一层的平均值。
66+
67+
具体地,我们定义一个队列 $q$,初始时将根节点加入队列。每次将队列中的所有节点取出,计算这些节点的平均值,加入答案数组中,并将这些节点的子节点加入队列。重复这一过程,直到队列为空。
68+
69+
时间复杂度 $O(n)$,空间复杂度 $O(n)$。其中 $n$ 是二叉树的节点个数。
70+
6571
<!-- tabs:start -->
6672

6773
#### Python3
@@ -159,8 +165,12 @@ public:
159165
root = q.front();
160166
q.pop();
161167
s += root->val;
162-
if (root->left) q.push(root->left);
163-
if (root->right) q.push(root->right);
168+
if (root->left) {
169+
q.push(root->left);
170+
}
171+
if (root->right) {
172+
q.push(root->right);
173+
}
164174
}
165175
ans.push_back(s * 1.0 / n);
166176
}
@@ -227,29 +237,30 @@ func averageOfLevels(root *TreeNode) []float64 {
227237
use std::rc::Rc;
228238
use std::cell::RefCell;
229239
use std::collections::VecDeque;
240+
230241
impl Solution {
231242
pub fn average_of_levels(root: Option<Rc<RefCell<TreeNode>>>) -> Vec<f64> {
232-
if root.is_none() {
233-
return Vec::new();
234-
}
235-
243+
let mut ans = vec![];
236244
let mut q = VecDeque::new();
237-
q.push_back(Rc::clone(&root.unwrap()));
238-
let mut ans = Vec::new();
245+
if let Some(root_node) = root {
246+
q.push_back(root_node);
247+
}
239248
while !q.is_empty() {
240249
let n = q.len();
241-
let mut sum = 0.0;
250+
let mut s: i64 = 0;
242251
for _ in 0..n {
243-
let node = q.pop_front().unwrap();
244-
sum += node.borrow().val as f64;
245-
if node.borrow().left.is_some() {
246-
q.push_back(Rc::clone(node.borrow().left.as_ref().unwrap()));
247-
}
248-
if node.borrow().right.is_some() {
249-
q.push_back(Rc::clone(node.borrow().right.as_ref().unwrap()));
252+
if let Some(node) = q.pop_front() {
253+
let node_borrow = node.borrow();
254+
s += node_borrow.val as i64;
255+
if let Some(left) = node_borrow.left.clone() {
256+
q.push_back(left);
257+
}
258+
if let Some(right) = node_borrow.right.clone() {
259+
q.push_back(right);
260+
}
250261
}
251262
}
252-
ans.push(sum / (n as f64));
263+
ans.push((s as f64) / (n as f64));
253264
}
254265
ans
255266
}
@@ -276,18 +287,15 @@ var averageOfLevels = function (root) {
276287
const ans = [];
277288
while (q.length) {
278289
const n = q.length;
290+
const nq = [];
279291
let s = 0;
280-
for (let i = 0; i < n; ++i) {
281-
root = q.shift();
282-
s += root.val;
283-
if (root.left) {
284-
q.push(root.left);
285-
}
286-
if (root.right) {
287-
q.push(root.right);
288-
}
292+
for (const { val, left, right } of q) {
293+
s += val;
294+
left && nq.push(left);
295+
right && nq.push(right);
289296
}
290297
ans.push(s / n);
298+
q.splice(0, q.length, ...nq);
291299
}
292300
return ans;
293301
};
@@ -299,7 +307,13 @@ var averageOfLevels = function (root) {
299307

300308
<!-- solution:start -->
301309

302-
### 方法二
310+
### 方法二:DFS
311+
312+
我们也可以使用深度优先搜索的方法,来计算每一层的平均值。
313+
314+
具体地,我们定义一个数组 $s$,其中 $s[i]$ 是一个二元组,表示第 $i$ 层的节点值之和以及节点个数。我们对树进行深度优先搜索,对于每一个节点,我们将节点的值加到对应的 $s[i]$ 中,并将节点个数加一。最后,对于每一个 $s[i]$,我们计算平均值,加入答案数组中。
315+
316+
时间复杂度 $O(n)$,空间复杂度 $O(n)$。其中 $n$ 是二叉树的节点个数。
303317

304318
<!-- tabs:start -->
305319

@@ -478,8 +492,8 @@ func averageOfLevels(root *TreeNode) []float64 {
478492
* @return {number[]}
479493
*/
480494
var averageOfLevels = function (root) {
481-
let s = [];
482-
let cnt = [];
495+
const s = [];
496+
const cnt = [];
483497
function dfs(root, i) {
484498
if (!root) {
485499
return;
@@ -495,11 +509,7 @@ var averageOfLevels = function (root) {
495509
dfs(root.right, i + 1);
496510
}
497511
dfs(root, 0);
498-
let ans = [];
499-
for (let i = 0; i < s.length; ++i) {
500-
ans.push(s[i] / cnt[i]);
501-
}
502-
return ans;
512+
return s.map((v, i) => v / cnt[i]);
503513
};
504514
```
505515

solution/0600-0699/0637.Average of Levels in Binary Tree/README_EN.md

+45-35
Original file line numberDiff line numberDiff line change
@@ -52,7 +52,13 @@ Hence return [3, 14.5, 11].
5252

5353
<!-- solution:start -->
5454

55-
### Solution 1
55+
### Solution 1: BFS
56+
57+
We can use the Breadth-First Search (BFS) method to traverse the nodes of each level and calculate the average value of each level.
58+
59+
Specifically, we define a queue $q$, initially adding the root node to the queue. Each time, we take out all the nodes in the queue, calculate their average value, add it to the answer array, and then add their child nodes to the queue. Repeat this process until the queue is empty.
60+
61+
The time complexity is $O(n)$, and the space complexity is $O(n)$. Here, $n$ is the number of nodes in the binary tree.
5662

5763
<!-- tabs:start -->
5864

@@ -151,8 +157,12 @@ public:
151157
root = q.front();
152158
q.pop();
153159
s += root->val;
154-
if (root->left) q.push(root->left);
155-
if (root->right) q.push(root->right);
160+
if (root->left) {
161+
q.push(root->left);
162+
}
163+
if (root->right) {
164+
q.push(root->right);
165+
}
156166
}
157167
ans.push_back(s * 1.0 / n);
158168
}
@@ -219,29 +229,30 @@ func averageOfLevels(root *TreeNode) []float64 {
219229
use std::rc::Rc;
220230
use std::cell::RefCell;
221231
use std::collections::VecDeque;
232+
222233
impl Solution {
223234
pub fn average_of_levels(root: Option<Rc<RefCell<TreeNode>>>) -> Vec<f64> {
224-
if root.is_none() {
225-
return Vec::new();
226-
}
227-
235+
let mut ans = vec![];
228236
let mut q = VecDeque::new();
229-
q.push_back(Rc::clone(&root.unwrap()));
230-
let mut ans = Vec::new();
237+
if let Some(root_node) = root {
238+
q.push_back(root_node);
239+
}
231240
while !q.is_empty() {
232241
let n = q.len();
233-
let mut sum = 0.0;
242+
let mut s: i64 = 0;
234243
for _ in 0..n {
235-
let node = q.pop_front().unwrap();
236-
sum += node.borrow().val as f64;
237-
if node.borrow().left.is_some() {
238-
q.push_back(Rc::clone(node.borrow().left.as_ref().unwrap()));
239-
}
240-
if node.borrow().right.is_some() {
241-
q.push_back(Rc::clone(node.borrow().right.as_ref().unwrap()));
244+
if let Some(node) = q.pop_front() {
245+
let node_borrow = node.borrow();
246+
s += node_borrow.val as i64;
247+
if let Some(left) = node_borrow.left.clone() {
248+
q.push_back(left);
249+
}
250+
if let Some(right) = node_borrow.right.clone() {
251+
q.push_back(right);
252+
}
242253
}
243254
}
244-
ans.push(sum / (n as f64));
255+
ans.push((s as f64) / (n as f64));
245256
}
246257
ans
247258
}
@@ -268,18 +279,15 @@ var averageOfLevels = function (root) {
268279
const ans = [];
269280
while (q.length) {
270281
const n = q.length;
282+
const nq = [];
271283
let s = 0;
272-
for (let i = 0; i < n; ++i) {
273-
root = q.shift();
274-
s += root.val;
275-
if (root.left) {
276-
q.push(root.left);
277-
}
278-
if (root.right) {
279-
q.push(root.right);
280-
}
284+
for (const { val, left, right } of q) {
285+
s += val;
286+
left && nq.push(left);
287+
right && nq.push(right);
281288
}
282289
ans.push(s / n);
290+
q.splice(0, q.length, ...nq);
283291
}
284292
return ans;
285293
};
@@ -291,7 +299,13 @@ var averageOfLevels = function (root) {
291299

292300
<!-- solution:start -->
293301

294-
### Solution 2
302+
### Solution 2: DFS
303+
304+
We can also use the Depth-First Search (DFS) method to calculate the average value of each level.
305+
306+
Specifically, we define an array $s$, where $s[i]$ is a tuple representing the sum of node values and the number of nodes at the $i$-th level. We perform a depth-first search on the tree. For each node, we add the node's value to the corresponding $s[i]$ and increment the node count by one. Finally, for each $s[i]$, we calculate the average value and add it to the answer array.
307+
308+
The time complexity is $O(n)$, and the space complexity is $O(n)$. Here, $n$ is the number of nodes in the binary tree.
295309

296310
<!-- tabs:start -->
297311

@@ -470,8 +484,8 @@ func averageOfLevels(root *TreeNode) []float64 {
470484
* @return {number[]}
471485
*/
472486
var averageOfLevels = function (root) {
473-
let s = [];
474-
let cnt = [];
487+
const s = [];
488+
const cnt = [];
475489
function dfs(root, i) {
476490
if (!root) {
477491
return;
@@ -487,11 +501,7 @@ var averageOfLevels = function (root) {
487501
dfs(root.right, i + 1);
488502
}
489503
dfs(root, 0);
490-
let ans = [];
491-
for (let i = 0; i < s.length; ++i) {
492-
ans.push(s[i] / cnt[i]);
493-
}
494-
return ans;
504+
return s.map((v, i) => v / cnt[i]);
495505
};
496506
```
497507

solution/0600-0699/0637.Average of Levels in Binary Tree/Solution.cpp

+6-2
Original file line numberDiff line numberDiff line change
@@ -21,8 +21,12 @@ class Solution {
2121
root = q.front();
2222
q.pop();
2323
s += root->val;
24-
if (root->left) q.push(root->left);
25-
if (root->right) q.push(root->right);
24+
if (root->left) {
25+
q.push(root->left);
26+
}
27+
if (root->right) {
28+
q.push(root->right);
29+
}
2630
}
2731
ans.push_back(s * 1.0 / n);
2832
}

solution/0600-0699/0637.Average of Levels in Binary Tree/Solution.js

+6-9
Original file line numberDiff line numberDiff line change
@@ -15,18 +15,15 @@ var averageOfLevels = function (root) {
1515
const ans = [];
1616
while (q.length) {
1717
const n = q.length;
18+
const nq = [];
1819
let s = 0;
19-
for (let i = 0; i < n; ++i) {
20-
root = q.shift();
21-
s += root.val;
22-
if (root.left) {
23-
q.push(root.left);
24-
}
25-
if (root.right) {
26-
q.push(root.right);
27-
}
20+
for (const { val, left, right } of q) {
21+
s += val;
22+
left && nq.push(left);
23+
right && nq.push(right);
2824
}
2925
ans.push(s / n);
26+
q.splice(0, q.length, ...nq);
3027
}
3128
return ans;
3229
};

solution/0600-0699/0637.Average of Levels in Binary Tree/Solution.rs

+16-15
Original file line numberDiff line numberDiff line change
@@ -19,29 +19,30 @@
1919
use std::rc::Rc;
2020
use std::cell::RefCell;
2121
use std::collections::VecDeque;
22+
2223
impl Solution {
2324
pub fn average_of_levels(root: Option<Rc<RefCell<TreeNode>>>) -> Vec<f64> {
24-
if root.is_none() {
25-
return Vec::new();
26-
}
27-
25+
let mut ans = vec![];
2826
let mut q = VecDeque::new();
29-
q.push_back(Rc::clone(&root.unwrap()));
30-
let mut ans = Vec::new();
27+
if let Some(root_node) = root {
28+
q.push_back(root_node);
29+
}
3130
while !q.is_empty() {
3231
let n = q.len();
33-
let mut sum = 0.0;
32+
let mut s: i64 = 0;
3433
for _ in 0..n {
35-
let node = q.pop_front().unwrap();
36-
sum += node.borrow().val as f64;
37-
if node.borrow().left.is_some() {
38-
q.push_back(Rc::clone(node.borrow().left.as_ref().unwrap()));
39-
}
40-
if node.borrow().right.is_some() {
41-
q.push_back(Rc::clone(node.borrow().right.as_ref().unwrap()));
34+
if let Some(node) = q.pop_front() {
35+
let node_borrow = node.borrow();
36+
s += node_borrow.val as i64;
37+
if let Some(left) = node_borrow.left.clone() {
38+
q.push_back(left);
39+
}
40+
if let Some(right) = node_borrow.right.clone() {
41+
q.push_back(right);
42+
}
4243
}
4344
}
44-
ans.push(sum / (n as f64));
45+
ans.push((s as f64) / (n as f64));
4546
}
4647
ans
4748
}

solution/0600-0699/0637.Average of Levels in Binary Tree/Solution2.js

+3-7
Original file line numberDiff line numberDiff line change
@@ -11,8 +11,8 @@
1111
* @return {number[]}
1212
*/
1313
var averageOfLevels = function (root) {
14-
let s = [];
15-
let cnt = [];
14+
const s = [];
15+
const cnt = [];
1616
function dfs(root, i) {
1717
if (!root) {
1818
return;
@@ -28,9 +28,5 @@ var averageOfLevels = function (root) {
2828
dfs(root.right, i + 1);
2929
}
3030
dfs(root, 0);
31-
let ans = [];
32-
for (let i = 0; i < s.length; ++i) {
33-
ans.push(s[i] / cnt[i]);
34-
}
35-
return ans;
31+
return s.map((v, i) => v / cnt[i]);
3632
};

0 commit comments

Comments
 (0)