You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
Copy file name to clipboardExpand all lines: solution/0600-0699/0637.Average of Levels in Binary Tree/README_EN.md
+45-35
Original file line number
Diff line number
Diff line change
@@ -52,7 +52,13 @@ Hence return [3, 14.5, 11].
52
52
53
53
<!-- solution:start -->
54
54
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.
@@ -268,18 +279,15 @@ var averageOfLevels = function (root) {
268
279
constans= [];
269
280
while (q.length) {
270
281
constn=q.length;
282
+
constnq= [];
271
283
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);
281
288
}
282
289
ans.push(s / n);
290
+
q.splice(0, q.length, ...nq);
283
291
}
284
292
return ans;
285
293
};
@@ -291,7 +299,13 @@ var averageOfLevels = function (root) {
291
299
292
300
<!-- solution:start -->
293
301
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.
0 commit comments