#637

Average of Levels in Binary Tree

Easy
TreeDepth-First SearchBreadth-First SearchBinary TreeBreadth-First SearchLevel Order Traversal
LeetCode ↗

Approaches

Brute ForceOptimal
Complexity Comparison
Brute ForceOptimal Solution
Time
O(n²)
O(n)
Space
O(1)
O(n)
💡

Intuition

Time O(n)Space O(n)

The optimal approach uses a breadth-first search (BFS) to traverse the tree level by level, calculating the average in a single pass for each level.

⚙️

Algorithm

4 steps
  1. 1Step 1: Initialize a queue and add the root node.
  2. 2Step 2: While the queue is not empty, process all nodes at the current level.
  3. 3Step 3: For each node, add its value to a sum and enqueue its children.
  4. 4Step 4: After processing all nodes at the current level, calculate the average and store it.
solution.py25 lines
1# Full working Python code
2class TreeNode:
3    def __init__(self, val=0, left=None, right=None):
4        self.val = val
5        self.left = left
6        self.right = right
7
8class Solution:
9    def averageOfLevels(self, root: TreeNode):
10        if not root:
11            return []
12        result = []
13        queue = [root]
14        while queue:
15            level_sum = 0
16            count = len(queue)
17            for _ in range(count):
18                node = queue.pop(0)
19                level_sum += node.val
20                if node.left:
21                    queue.append(node.left)
22                if node.right:
23                    queue.append(node.right)
24            result.append(level_sum / count)
25        return result

Complexity note: This complexity is due to visiting each node once, and the space complexity arises from the queue used for BFS.

  • 1Understanding tree traversal methods is crucial.
  • 2BFS is often more efficient for level-based problems.

Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.