Problem 559

Abstract / Summary

Find the greatest number of levels in a tree where each node can have many children.

Note

The full problem description, including helpful examples, can be found on LeetCode.

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)
8 lines | 227 bytes | submitted September 1, 2023 | GitHub   tab size 4 | low complexity

Difficulty

This problem is ranked as
easy medium hard

and has an acceptance rate of about 74% (400k+ submissions).

Typical patterns to solve this problem:
  • Breadth First Search
  • Depth First Search
  • Tree
I solved 663 easy, 1250 medium and 309 hard problems

AI Disclaimer

Every single line of code was written by me, 100% from scratch, between August 2023 and August 2024.
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.
LeetCode profile | GitHub repo

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.

written by openai gpt

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.

written by google gemini

Code Quality

Several LLMs ranked my code quality on a scale from 1 (very poor) to 10 (outstanding):
n = 27 | median = 8 | μ = 8.07 | σ = 1.12

Complexity Analysis

Time: linear
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
generated automatically

Other Solutions

I wrote a basic crawler to find other solutions to that problem.
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
36 links | 23 authors | 9 languages

Videos

6 videos   did my crawler come up with invalid videos ? drop me a line.

Similar Problems

1 similar problem

Solved On The Same Day

30 solutions   September 1, 2023

Extra

There are a few extra pages giving you some insights into my setup:
  • 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