Python 0637.py
class Solution:
def averageOfLevels(self, root: Optional[TreeNode]) -> List[float]:
sums = defaultdict(int)
nums = defaultdict(int)
def deeper(node, depth):
if node:
sums[depth] += node.val
nums[depth] += 1
deeper(node.left, depth + 1)
deeper(node.right, depth + 1)
deeper(root, 0)
return [ sums[i] / nums[i] for i in range(len(sums)) ]
Difficulty
and has an acceptance rate of about 75% (1+ million submissions).
Typical patterns to solve this problem:
- Binary Tree
- Breadth First Search
- Depth First Search
- Tree
AI Disclaimer
However, two years later I set up this website and used various AI tools to generate most of the walkthrough / explanations below.
See this dedicated page for more details.
Code Walkthrough
Overview
The provided implementation computes the average value of nodes at each depth level of a binary tree. It traverses the tree once, aggregates the sum of node values and the count of nodes per level, and finally produces a list where each entry corresponds to the average for a particular depth, starting from the root level (depth 0).
Key Steps
Initialization of Aggregation Containers
sums = defaultdict(int)
nums = defaultdict(int)
Two dictionaries are created using defaultdict with an integer default. sums records the cumulative value of nodes for each depth, while nums tracks how many nodes have been encountered at that depth. The choice of defaultdict eliminates the need for explicit existence checks before updating a key, streamlining the accumulation logic.
Recursive Depth-First Traversal
def deeper(node, depth):
if node:
sums[depth] += node.val
nums[depth] += 1
deeper(node.left, depth + 1)
deeper(node.right, depth + 1)
A nested helper function deeper performs a depth-first search. For each non-null node, it updates the running total and count for the current depth, then recurses on the left and right children with an incremented depth value. The conditional if node: ensures that leaf children (None) are safely ignored, preventing attempts to access attributes on a null reference.
The recursion naturally explores all branches of the tree, handling trees of arbitrary shape-including completely unbalanced structures-without requiring auxiliary data structures such as explicit stacks or queues.
Invocation of the Traversal
deeper(root, 0)
The traversal is launched with the root node and an initial depth of zero. If the root itself is None, the guard inside deeper prevents any updates, leaving the aggregation dictionaries empty.
Construction of the Result List
return [ sums[i] / nums[i] for i in range(len(sums)) ]
After the traversal completes, a list comprehension iterates over the range of recorded depths. For each depth index i, it divides the accumulated sum by the node count, yielding the average value for that level. The order of the list aligns with increasing depth because the keys in sums and nums are sequentially populated starting from zero.
Edge Cases Handled
When the input tree is empty (root is None), the recursive function never updates the dictionaries, resulting in len(sums) being zero. Consequently, the list comprehension iterates over an empty range and the method returns an empty list, correctly representing the absence of any levels.
A tree consisting of a single node triggers a single update at depth 0, producing a list with one element equal to the node’s value. The algorithm also gracefully processes trees with varying branch lengths; each recursive call carries its own depth counter, ensuring that nodes are aggregated under the correct level regardless of how deep or shallow different subtrees are.
Performance Optimizations
The use of defaultdict removes the overhead of key existence checks during accumulation, allowing direct addition to the stored totals. By performing both sum and count updates within the same recursive pass, the solution avoids multiple traversals of the tree, achieving a single-pass aggregation. The final averaging step leverages a list comprehension, which is executed in C-level loops under the hood, providing a fast and memory-efficient way to produce the output list.
Overall, the implementation balances clarity with efficiency, employing Python’s built-in data structures and language features to minimize boilerplate while maintaining linear traversal characteristics.
ELI5 - Simplified Explanation
Imagine a giant tree standing upside down, where the starting point is at the very top. This code is like a little explorer traveling down every branch to visit every single spot on the tree.
As the explorer visits each spot, it keeps a notebook to record two things. First, it writes down how far down the tree it is, which is called the depth. Second, it adds up the number written on the spot it is currently standing on. The explorer also counts how many spots are at that exact same depth.
The explorer starts at the top and goes as deep as it can, always remembering to check both the left side and the right side of every point. If it finds a new branch, it goes down that one too. By the time it has checked every single part of the tree, it has a complete list of all the numbers at each level and how many spots there are at each level. After finishing the work, it takes the total sum of numbers for a level and divides that by the number of spots found at that same level to figure out the average.
Code Quality
Complexity Analysis
As a rule of thumb, the maximum input size for one second execution time is
- factorial: up to 10 elements
- exponential: up to 20 elements
- polynomial: a few thousand elements
- loglinear: up to 100,000 elements
- linear: a few million elements
- logarithmic: a billion elements
- constant: practically unlimited
Other Solutions
Obviously, I did that after I solved the problem myself.
In general, AlgoMonster and WalkCCC solutions are high-quality and always worth a look.
I haven't checked most of the other solutions, but they might be helpful as well.
And of course, the LeetCode forum is always a good place (or even the best) to look for alternative approaches.
(click on a column header to sort the table)
| author | ||||||||||||
|---|---|---|---|---|---|---|---|---|---|---|---|---|
| author | solutions | |||||||||||
| www | AlgoMonster | C++ | Java | Python | TS | |||||||
| WalkCCC | C++ | Java | ||||||||||
| leetcode.ca | C++ | Java | Python | JS | Rust | Go | ||||||
| LeetcodeHelp | C++ | Java | Python | |||||||||
| Progiez | C++ | Java | Python | |||||||||
| github | BigEggStudy | C# | ||||||||||
| black-shadows | C++ | |||||||||||
| chandansgowda | Python | |||||||||||
| charles-wangkai | Java | |||||||||||
| DimitrisJim | C | |||||||||||
| everthis | JS | |||||||||||
| fartem | Ruby | |||||||||||
| fengvyi | C++ | |||||||||||
| gouthampradhan | Java | |||||||||||
| halfrost | Go | |||||||||||
| JoshCrozier | JS | |||||||||||
| keineahnung2345 | C++ | |||||||||||
| Krazune | C++ | |||||||||||
| linouk23 | C++ | |||||||||||
| lkwq007 | Python | |||||||||||
| ruoru | Rust | |||||||||||
| shreymehul | C# | |||||||||||
| sonugiri1043 | C++ | |||||||||||
| suxrobGM | C# | |||||||||||
| varunu28 | Java | |||||||||||
| vthwang | Java | |||||||||||
| wisdompeak | C++ | |||||||||||
| yuanliu666 | Kotlin | |||||||||||
| YuriSpiridonov | Python | |||||||||||
| zfang399 | C++ | |||||||||||
| AlgoMonster | C++, Python, Java, TypeScript | |||||||||||
| WalkCCC | C++, Java | |||||||||||
| leetcode.ca | C++, Go, Java, JavaScript, Python, Rust | |||||||||||
| LeetcodeHelp | C++, Java, Python | |||||||||||
| Progiez | C++, Java, Python | |||||||||||
| BigEggStudy | C# | |||||||||||
| black-shadows | C++, C++ | |||||||||||
| chandansgowda | Python | |||||||||||
| charles-wangkai | Java | |||||||||||
| DimitrisJim | C | |||||||||||
| everthis | JavaScript | |||||||||||
| fartem | Ruby | |||||||||||
| fengvyi | C++ | |||||||||||
| gouthampradhan | Java | |||||||||||
| halfrost | Go | |||||||||||
| JoshCrozier | JavaScript | |||||||||||
| keineahnung2345 | C++ | |||||||||||
| Krazune | C++ | |||||||||||
| linouk23 | C++ | |||||||||||
| lkwq007 | Python | |||||||||||
| ruoru | Rust | |||||||||||
| shreymehul | C# | |||||||||||
| sonugiri1043 | C++ | |||||||||||
| suxrobGM | C# | |||||||||||
| varunu28 | Java | |||||||||||
| vthwang | Java | |||||||||||
| wisdompeak | C++ | |||||||||||
| yuanliu666 | Kotlin | |||||||||||
| YuriSpiridonov | Python | |||||||||||
| zfang399 | C++ |
Videos
Similar Problems
- problem 107: Binary Tree Level Order Traversal II
Solved On The Same Day
- problem 144: Binary Tree Preorder Traversal
- problem 145: Binary Tree Postorder Traversal
- problem 222: Count Complete Tree Nodes
- problem 404: Sum of Left Leaves
- problem 501: Find Mode in Binary Search Tree
- problem 543: Diameter of Binary Tree
- problem 559: Maximum Depth of N-ary Tree
- problem 589: N-ary Tree Preorder Traversal
- problem 590: N-ary Tree Postorder Traversal
- problem 700: Search in a Binary Search Tree
- problem 703: Kth Largest Element in a Stream
- problem 79: Word Search
- problem 81: Search in Rotated Sorted Array II
- problem 97: Interleaving String
- problem 99: Recover Binary Search Tree
- problem 173: Binary Search Tree Iterator
- problem 199: Binary Tree Right Side View
- problem 230: Kth Smallest Element in a BST
- problem 235: Lowest Common Ancestor of a Binary Search Tree
- problem 341: Flatten Nested List Iterator
- problem 429: N-ary Tree Level Order Traversal
- problem 508: Most Frequent Subtree Sum
- problem 513: Find Bottom Left Tree Value
- problem 538: Convert BST to Greater Tree
- problem 65: Valid Number
- problem 85: Maximal Rectangle
- problem 87: Scramble String
- problem 126: Word Ladder II
- problem 127: Word Ladder
Extra
- Tech Stack - my development environment and tools
- AI - how AI helped me create this website (NOT solving the problems)
- Progress - progression over time
- Quality - code quality