Sponsored
Sponsored
This approach uses a Breadth-First Search (BFS) strategy to traverse the binary tree level by level. For each level, we calculate the sum of node values and the count of nodes, then compute the average for each level. The BFS technique helps in handling each level independently using a queue.
Time Complexity: O(N)
, where N
is the number of nodes in the tree, as each node is processed once.
Space Complexity: O(M)
, where M
is the maximum number of nodes at any level, corresponding to the queue holding these nodes.
1class TreeNode {
2 constructor(val, left = null, right = null) {
3 this.val = val;
4 this.left = left;
5 this.right = right;
6 }
7}
8
9function averageOfLevels(root) {
10 const averages = [];
11 const queue = [root];
12 while (queue.length > 0) {
13 const count = queue.length;
14 let sum = 0;
15 for (let i = 0; i < count; i++) {
16 const node = queue.shift();
17 sum += node.val;
18 if (node.left) queue.push(node.left);
19 if (node.right) queue.push(node.right);
20 }
21 averages.push(sum / count);
22 }
23 return averages;
24}
25
26// Example usage
27const a = new TreeNode(3);
28const b = new TreeNode(9);
29const c = new TreeNode(20);
30const d = new TreeNode(15);
31const e = new TreeNode(7);
32
33a.left = b;
34a.right = c;
35c.left = d;
36c.right = e;
37
38console.log(averageOfLevels(a));
In this JavaScript solution, a simple queue based BFS is used. Nodes are processed and summed at each level to compute averages, with results returned once all levels are processed.
This approach makes use of Depth-First Search (DFS) combined with pre-order traversal. The key idea is to traverse the tree, keeping track of the sum of node values and the count of nodes at each level. Recursive traversal helps gather the necessary values efficiently for averaging.
Time Complexity: O(N)
, where N
signifies the number of tree nodes.
Space Complexity: O(H)
, where H
is the height of the tree due to recursion stack.
The Python approach involves DFS for pre-order traversal to gather sums and counts of node values recursively. Calculated averages per level complete the method's goal.