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 <stdio.h>
2#include <stdlib.h>
3#include <math.h>
4
5struct TreeNode {
6 int val;
7 struct TreeNode *left;
8 struct TreeNode *right;
9};
10
11struct QueueNode {
12 struct TreeNode *node;
13 struct QueueNode *next;
14};
15
16struct Queue {
17 struct QueueNode *front, *rear;
18};
19
20struct Queue* createQueue() {
21 struct Queue* q = (struct Queue*)malloc(sizeof(struct Queue));
22 q->front = q->rear = NULL;
23 return q;
24}
25
26void enqueue(struct Queue* q, struct TreeNode* node) {
27 struct QueueNode* newNode = (struct QueueNode*)malloc(sizeof(struct QueueNode));
28 newNode->node = node;
29 newNode->next = NULL;
30 if (q->rear == NULL) {
31 q->front = q->rear = newNode;
32 return;
33 }
34 q->rear->next = newNode;
35 q->rear = newNode;
36}
37
38struct TreeNode* dequeue(struct Queue* q) {
39 if (q->front == NULL) return NULL;
40 struct QueueNode* temp = q->front;
41 q->front = q->front->next;
42 if (q->front == NULL) q->rear = NULL;
43 struct TreeNode* node = temp->node;
44 free(temp);
45 return node;
46}
47
48int isQueueEmpty(struct Queue* q) {
49 return q->front == NULL;
50}
51
52// Function to find average of nodes at each level
53void averageOfLevels(struct TreeNode* root) {
54 if (!root) return;
55 struct Queue* q = createQueue();
56 enqueue(q, root);
57 while (!isQueueEmpty(q)) {
58 int count = 0;
59 double sum = 0;
60 struct Queue* level = createQueue();
61 while (!isQueueEmpty(q)) {
62 struct TreeNode* node = dequeue(q);
63 sum += node->val;
64 count++;
65 if (node->left) enqueue(level, node->left);
66 if (node->right) enqueue(level, node->right);
67 }
68 printf("%.5f ", sum / count);
69 free(q);
70 q = level;
71 }
72}
73
74int main() {
75 /* Create Binary tree with nodes */
76 struct TreeNode a, b, c, d, e;
77 a.val = 3; a.left = &b; a.right = &c;
78 b.val = 9; b.left = NULL; b.right = NULL;
79 c.val = 20; c.left = &d; c.right = &e;
80 d.val = 15; d.left = NULL; d.right = NULL;
81 e.val = 7; e.left = NULL; e.right = NULL;
82
83 averageOfLevels(&a);
84 return 0;
85}
In this C solution, we implement the BFS traversal using a queue. We enqueue the root node first, then for each node, enqueue its children. The sum and count for each level are calculated, and averages are printed. This method ensures that each level is fully processed before the next begins.
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.
1using System.Collections.Generic;
public class TreeNode {
public int val;
public TreeNode left;
public TreeNode right;
public TreeNode(int x) { val = x; }
}
public class Solution {
public IList<double> AverageOfLevels(TreeNode root) {
List<long> sums = new List<long>();
List<int> counts = new List<int>();
dfs(root, 0, sums, counts);
List<double> averages = new List<double>();
for (int i = 0; i < sums.Count; i++) {
averages.Add((double)sums[i] / counts[i]);
}
return averages;
}
private void dfs(TreeNode node, int level, List<long> sums, List<int> counts) {
if (node == null) return;
if (level == sums.Count) {
sums.Add(node.val);
counts.Add(1);
} else {
sums[level] += node.val;
counts[level]++;
}
dfs(node.left, level + 1, sums, counts);
dfs(node.right, level + 1, sums, counts);
}
public static void Main(string[] args) {
TreeNode a = new TreeNode(3);
TreeNode b = new TreeNode(9);
TreeNode c = new TreeNode(20);
TreeNode d = new TreeNode(15);
TreeNode e = new TreeNode(7);
a.left = b;
a.right = c;
c.left = d;
c.right = e;
Solution solution = new Solution();
IList<double> result = solution.AverageOfLevels(a);
foreach (double avg in result) {
Console.Write(avg + " ");
}
}
}
The C# implementation uses DFS for traversing with lists managing the sums and counts for each level recursively, followed by level average computation.