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.
1#include <iostream>
2#include <queue>
3#include <vector>
4using namespace std;
5
6struct TreeNode {
7 int val;
8 TreeNode *left;
9 TreeNode *right;
10 TreeNode(int x) : val(x), left(NULL), right(NULL) {}
11};
12
13vector<double> averageOfLevels(TreeNode* root) {
14 vector<double> averages;
15 if (!root) return averages;
16 queue<TreeNode*> q;
17 q.push(root);
18 while (!q.empty()) {
19 long sum = 0, count = 0;
20 queue<TreeNode*> temp;
21 while (!q.empty()) {
22 TreeNode* node = q.front();
23 q.pop();
24 sum += node->val;
25 count++;
26 if (node->left) temp.push(node->left);
27 if (node->right) temp.push(node->right);
28 }
29 averages.push_back((double)sum / count);
30 swap(q, temp);
31 }
32 return averages;
33}
34
35int main() {
36 /* Create Binary tree with nodes */
37 TreeNode a(3), b(9), c(20), d(15), e(7);
38 a.left = &b;
39 a.right = &c;
40 c.left = &d;
41 c.right = &e;
42
43 vector<double> result = averageOfLevels(&a);
44 for (double avg : result) {
45 cout << avg << " ";
46 }
47 return 0;
48}
In the C++ solution, a queue supports the BFS traversal of the tree. Each level computes the sum of node values to calculate the average. The method ensures that for each level, all nodes are processed before proceeding to the next.
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.