root of a binary tree, return the average value of the nodes on each level in the form of an array. Answers within 10-5 of the actual answer will be accepted.
Example 1:
Input: root = [3,9,20,null,null,15,7] Output: [3.00000,14.50000,11.00000] Explanation: The average value of nodes on level 0 is 3, on level 1 is 14.5, and on level 2 is 11. Hence return [3, 14.5, 11].
Example 2:
Input: root = [3,9,20,15,7] Output: [3.00000,14.50000,11.00000]
Constraints:
[1, 104].-231 <= Node.val <= 231 - 1Problem Overview: You are given the root of a binary tree and need to compute the average value of nodes at every depth level. The result should return one average per level, starting from the root and moving downward.
Approach 1: Breadth-First Search (BFS) Using Queue (Time: O(n), Space: O(w))
This approach performs a level-order traversal using a queue. Push the root into the queue, then repeatedly process nodes level by level. For each level, track the number of nodes currently in the queue, iterate through them, accumulate their values, and push their children into the queue. After processing the level, compute the average as levelSum / levelSize and append it to the result list. BFS naturally groups nodes by depth, making it the most straightforward way to compute per-level aggregates in a breadth-first search traversal.
This method visits every node exactly once, giving O(n) time complexity where n is the number of nodes in the tree. Space complexity is O(w), where w is the maximum width of the tree (the largest number of nodes at any level). For balanced trees, this can approach O(n). In practice, BFS is usually the clearest and most interview-friendly solution for problems that require level-based processing.
Approach 2: Depth-First Search (DFS) With Pre-order Traversal (Time: O(n), Space: O(h))
The DFS solution uses recursion to traverse the tree while tracking the current depth. Maintain two arrays (or lists): one storing the cumulative sum of values per level and another storing the count of nodes per level. During a depth-first search, whenever you visit a node, check whether the current depth already exists in the arrays. If not, initialize it. Then update the sum and increment the node count for that level.
After the traversal completes, compute each level's average by dividing the stored sum by the count. The traversal itself still touches every node once, resulting in O(n) time complexity. Space complexity is O(h) for the recursion stack, where h is the height of the tree, plus the arrays that store level sums and counts. DFS works well when recursion feels more natural or when you want tighter control over traversal logic in a binary tree.
Recommended for interviews: The BFS queue solution is typically what interviewers expect first because the problem explicitly asks for level-based results. It maps directly to level-order traversal and keeps the implementation simple. Showing the DFS variant demonstrates deeper understanding of tree traversal patterns and how to aggregate values across recursion levels.
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.
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.
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.
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.
This C solution employs a depth-first approach that recursively calculates level sums and counts. The dfs function updates these for each node, with results computed for levels in the end.
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.
We can use the Breadth-First Search (BFS) method to traverse the nodes of each level and calculate the average value of each level.
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.
The time complexity is O(n), and the space complexity is O(n). Here, n is the number of nodes in the binary tree.
We can also use the Depth-First Search (DFS) method to calculate the average value of each level.
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.
The time complexity is O(n), and the space complexity is O(n). Here, n is the number of nodes in the binary tree.
Python
Java
C++
Go
JavaScript
| Approach | Complexity |
|---|---|
| Breadth-First Search (BFS) Using Queue | Time Complexity: |
| Depth-First Search (DFS) With Pre-order Traversal | Time Complexity: |
| BFS | — |
| DFS | — |
| Approach | Time | Space | When to Use |
|---|---|---|---|
| Breadth-First Search (BFS) Using Queue | O(n) | O(w) | Best when computing values level-by-level in a tree; most intuitive approach |
| Depth-First Search (DFS) With Pre-order Traversal | O(n) | O(h) | Useful when recursion is preferred or when aggregating results per depth |
LeetCode 637. Average of Levels in Binary Tree (Algorithm Explained) • Nick White • 14,522 views views
Watch 9 more video solutions →Practice Average of Levels in Binary Tree with our built-in code editor and test cases.
Practice on FleetCode