Python 0589.py
class Solution:
def preorder(self, root: 'Node') -> List[int]:
def deeper(node):
if node:
yield node.val
for i in node.children:
yield from deeper(i)
return deeper(root)
Difficulty
and has an acceptance rate of about 77% (600k+ submissions).
Typical patterns to solve this problem:
- Depth First Search
- Stack
- 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 Solution class with a preorder method that performs a preorder traversal of an N-ary tree. The traversal is expressed as a generator, allowing the caller to iterate over node values without materializing the entire result in memory. A nested helper function, deeper, carries out the recursive walk, yielding each node’s value before descending into its children.
Key Steps
The traversal logic is encapsulated in the inner function deeper. The first operation checks whether the current node exists; if it does, the node’s value is emitted immediately:
if node:
yield node.val
After emitting the current node’s value, the function iterates over the node’s children collection. For each child, it delegates to the same deeper function using yield from, which streams all values produced by the recursive call directly to the outer generator:
for i in node.children:
yield from deeper(i)
The public preorder method simply invokes deeper with the supplied root and returns the resulting generator object:
return deeper(root)
Edge Cases
When the input root is None, the condition if node: fails immediately, and the generator yields no values. This behavior gracefully handles an empty tree without raising exceptions.
If a node has an empty children list, the for loop iterates zero times. The generator still yields the node’s own value, correctly representing a leaf in the preorder sequence.
The recursive structure naturally accommodates trees of varying breadth and depth, ensuring that each node is visited exactly once regardless of how many children it possesses.
Performance Optimizations
The use of a generator (yield and yield from) provides lazy evaluation. Values are produced on demand, which minimizes peak memory consumption compared to building a full list of results. This is especially beneficial for large trees where storing all node values simultaneously could be prohibitive.
The yield from construct eliminates the need for explicit loops to forward values from recursive calls, reducing overhead and keeping the call stack succinct. By defining deeper as an inner function, the implementation benefits from closure capture of the surrounding scope, avoiding the overhead of passing additional parameters.
Overall, the design leverages Python’s generator mechanics to achieve an efficient, memory-friendly preorder traversal.
ELI5 - Simplified Explanation
Imagine a giant tree standing in a park. This tree is special because it has many branches, and on the end of every branch sits a little toy surprise. To find all the toys, imagine starting at the very top of the tree.
The code follows a simple rule to find everything. First, it looks at the toy right where it is standing. Once the toy is found, it looks to see if there are any tiny branches growing out from that spot. If it finds a branch, it travels down to the next level to check that branch for more toys. It keeps doing this over and over again, moving down each path one by one until every single toy in the whole tree has been found. It is just like exploring a big jungle gym where you visit the main toy first and then check all the paths connected to it before moving on to the next part of the tree.
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++ | Java | |||||||||
| leetcode.ca | C++ | Python | Java | Go | C | 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 | ||||||||||
| sonugiri1043 | C++ | ||||||||||
| suxrobGM | C# | ||||||||||
| trung-hn | Python | ||||||||||
| varunu28 | Java | ||||||||||
| vthwang | Java | ||||||||||
| yuanliu666 | Kotlin | ||||||||||
| YuriSpiridonov | Python | ||||||||||
| AlgoMonster | C++, Python, Java, TypeScript | ||||||||||
| WalkCCC | C++, Java | ||||||||||
| leetcode.ca | C, 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 | ||||||||||
| sonugiri1043 | C++ | ||||||||||
| suxrobGM | C# | ||||||||||
| trung-hn | Python | ||||||||||
| varunu28 | Java | ||||||||||
| vthwang | Java | ||||||||||
| yuanliu666 | Kotlin | ||||||||||
| YuriSpiridonov | Python |
Videos
Similar Problems
- problem 144: Binary Tree Preorder Traversal
- problem 428: Serialize and Deserialize N-ary Tree
- problem 429: N-ary Tree Level Order Traversal
- problem 590: N-ary Tree Postorder Traversal
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 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