Problem 589

Abstract / Summary

Given the root of an n-ary tree return the preorder traversal of its nodes values as a list.

Note

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

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)
9 lines | 264 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 77% (600k+ submissions).

Typical patterns to solve this problem:
  • Depth First Search
  • Stack
  • 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 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.

written by openai gpt

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.

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 = 7 | μ = 7.19 | σ = 1.31

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++ 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
37 links | 24 authors | 10 languages

Videos

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

Similar Problems

2 similar problems

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