637. Average of Levels in Binary Tree
Tags:
Easy
Skills:
Tree
June 24, 2025
04:32 AM
No headings found
Loading content...
Related Posts
Leetcode
No headings found
Related Posts
Leetcode
Problem
Bài toán yêu cầu tính giá trị trung bình của các node trên từng tầng của một binary tree và return về dưới dạng một mảng số thực, mỗi phần tử là trung bình của một tầng
Approach
Solution
1/**
2 * Definition for a binary tree node.
3 * class TreeNode {
4 * val: number
5 * left: TreeNode | null
6 * right: TreeNode | null
7 * constructor(val?: number, left?: TreeNode | null, right?: TreeNode | null) {
8 * this.val = (val===undefined ? 0 : val)
9 * this.left = (left===undefined ? null : left)
10 * this.right = (right===undefined ? null : right)
11 * }
12 * }
13 */
14
15function averageOfLevels(root: TreeNode | null): number[] {
16 const res: number[] = [];
17 if(!root) return [];
18 const queue: TreeNode[] = [root];
19 while(queue.length) {
20 const level_size = queue.length;
21 let sum = 0;
22 for(let i =0 ; i < level_size; i++) {
23 const node = queue.shift()!;
24 sum += node.val;
25 if(node.left) queue.push(node.left);
26 if(node.right) queue.push(node.right);
27 }
28 res.push(sum / level_size)
29 }
30 return res;
31};