Python 0559.py
class Solution:
def maxDepth(self, root: 'Node') -> int:
if not root:
return 0
if not root.children:
return 1
return 1 + max(self.maxDepth(i) for i in root.children)
Difficulty
and has an acceptance rate of about 74% (400k+ submissions).
Typical patterns to solve this problem:
- 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 defines a class Solution with a single method maxDepth. The method computes the maximum depth of an N-ary tree whose nodes are instances of a Node type that contains a children collection. The algorithm follows a classic recursive depth-first strategy: it descends into each child subtree, determines the deepest level among them, and aggregates the result with the current node’s contribution.
Key Steps
The entry point checks whether the supplied root reference is falsy. If the tree is empty, the method returns 0, establishing the base case for an absent structure.
if not root:
return 0
When a node exists but has no children, the method identifies it as a leaf. In this situation the depth contributed by the leaf itself is 1.
if not root.children:
return 1
For internal nodes that possess one or more children, the method invokes itself recursively for each child. The generator expression self.maxDepth(i) for i in root.children yields the depth of every child subtree without materializing an intermediate list. The built-in max function selects the greatest depth among those values, and the method adds 1 to account for the current node’s level.
return 1 + max(self.maxDepth(i) for i in root.children)
The recursion naturally propagates the depth information upward, culminating in the overall maximum depth of the tree.
Edge Cases
The code explicitly handles the scenario where the input tree is completely absent; the if not root guard returns 0, ensuring that callers receive a sensible numeric result rather than encountering an exception.
A second edge condition concerns leaf nodes. By checking if not root.children, the implementation treats any node lacking children as a terminal point, returning a depth of 1. This covers cases where a node’s children attribute might be an empty list, None, or any falsy collection, thereby preventing unnecessary recursive calls on empty iterables.
The recursive step also gracefully manages nodes with a single child, multiple children, or a heterogeneous mix of subtrees, because the generator expression iterates over whatever collection is present in root.children. No special handling is required for varying branching factors.
Performance Optimizations
The algorithm leverages Python’s generator expression inside the max call, which yields each child’s depth on demand. This approach avoids allocating a full list of depths, reducing memory pressure especially for trees with a large number of children per node.
By returning early for empty trees and leaf nodes, the method eliminates deeper recursive invocations that would otherwise compute redundant values. This early exit pattern trims the call stack depth for trivial subtrees, contributing to a more efficient traversal.
The use of the built-in max function provides a highly optimized C-level implementation for selecting the greatest depth among the generated values, which is faster than a manual loop written in pure Python.
Overall, the recursive structure combined with lazy evaluation and early returns yields a concise solution that operates with minimal overhead while correctly handling all structural variations of an N-ary tree.
ELI5 - Simplified Explanation
Imagine a big tree standing in a park. This tree has many branches, and those branches have smaller branches, and those even have tiny twigs at the very end. The code is like a little explorer trying to figure out how tall the tree is by climbing from the bottom all the way to the highest tip.
First, the explorer checks if there is any tree at all. If the ground is empty, there is no tree, so the height is nothing.
Next, the explorer looks to see if the branch they are standing on has any smaller branches coming out of it. If there are no other branches, the explorer knows they are at the very top, so the tree is just that one piece tall.
If the branch does have more little branches, the explorer asks each one of them to count how much further up they go. They look at all the little branches, pick the one that reaches the highest toward the sky, and then add one to that number to include the branch where they are currently standing. By doing this over and over, the explorer finds the longest path from the bottom to the very highest leaf.
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++ | Python | Java | TS | |||||
| WalkCCC | C++ | Python | Java | |||||||
| leetcode.ca | C++ | Python | Java | Go | TS | |||||
| LeetcodeHelp | C++ | Python | Java | |||||||
| Progiez | C++ | Python | Java | |||||||
| github | BigEggStudy | C# | ||||||||
| black-shadows | C++ | |||||||||
| chandansgowda | Python | |||||||||
| charles-wangkai | Java | |||||||||
| DimitrisJim | C | |||||||||
| everthis | JS | |||||||||
| fartem | Ruby | |||||||||
| halfrost | Go | |||||||||
| JoshCrozier | JS | |||||||||
| keineahnung2345 | C++ | |||||||||
| Krazune | C++ | |||||||||
| lkwq007 | Python | |||||||||
| lzl124631x | C++ | |||||||||
| shreymehul | C# | |||||||||
| sonugiri1043 | C++ | |||||||||
| suxrobGM | C# | |||||||||
| varunu28 | Java | |||||||||
| YuriSpiridonov | Python | |||||||||
| AlgoMonster | C++, Python, Java, TypeScript | |||||||||
| WalkCCC | C++, Python, Java | |||||||||
| leetcode.ca | C++, Go, Java, Python, TypeScript | |||||||||
| 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 | |||||||||
| halfrost | Go | |||||||||
| JoshCrozier | JavaScript | |||||||||
| keineahnung2345 | C++ | |||||||||
| Krazune | C++ | |||||||||
| lkwq007 | Python | |||||||||
| lzl124631x | C++ | |||||||||
| shreymehul | C# | |||||||||
| sonugiri1043 | C++ | |||||||||
| suxrobGM | C# | |||||||||
| varunu28 | Java | |||||||||
| YuriSpiridonov | Python |
Videos
Similar Problems
- problem 104: Maximum Depth of Binary Tree
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 589: N-ary Tree Preorder Traversal
- problem 590: N-ary Tree Postorder Traversal
- problem 637: Average of Levels in Binary Tree
- 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