Python 0144.py
class Solution:
def preorderTraversal(self, root: Optional[TreeNode]) -> List[int]:
def deeper(node):
if node:
yield node.val
yield from deeper(node.left)
yield from deeper(node.right)
yield from deeper(root)
Difficulty
and has an acceptance rate of about 76% (3+ million submissions).
Typical patterns to solve this problem:
- Binary Tree
- 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 single method, preorderTraversal, that returns the values of a binary tree in preorder (node, left subtree, right subtree). The method leverages a nested generator function to perform a depth-first walk and streams the results directly to the caller without constructing an intermediate collection.
Key Steps
The core of the algorithm resides in the inner generator deeper. This function receives a tree node and, if the node is not None, yields its value before recursively delegating to the left and right children. The use of yield from allows the generator to seamlessly forward all values produced by the recursive calls.
def deeper(node):
if node:
yield node.val
yield from deeper(node.left)
yield from deeper(node.right)
The outer method simply initiates the traversal by delegating to deeper with the root of the tree. The yield from expression at this level streams the entire preorder sequence to the caller.
yield from deeper(root)
Because deeper is a generator, the preorderTraversal method itself becomes a generator. When the caller iterates over the returned object, each node value is produced on demand.
Edge Cases Handled
When the input root is None, the initial call to deeper receives a None argument. The conditional if node: fails, causing the generator to terminate immediately without yielding any values. This behavior correctly represents an empty traversal result.
Leaf nodes are also covered naturally. For a leaf, both node.left and node.right are None. After yielding the leaf’s value, the recursive calls receive None, hit the guard condition, and return without further output. The generator therefore yields exactly one value for each leaf and proceeds to backtrack correctly.
Performance Optimizations
The implementation avoids allocating a list to hold the traversal order. By using generators and yield from, each node’s value is emitted as soon as it is visited, which minimizes memory consumption especially for large trees. The lazy nature of the generator means that only the portion of the tree required by the consumer is kept in memory at any moment.
The yield from construct reduces the overhead of manually iterating over the sub-generators. It forwards values directly, eliminating the need for explicit loops or temporary containers. This results in a concise control flow and a modest reduction in call-stack management overhead compared to a manual iteration approach.
Overall, the code delivers a clean, memory-efficient preorder traversal by combining recursion with Python’s generator facilities.
ELI5 - Simplified Explanation
Imagine you are exploring a giant treehouse where every room has a special toy and two little doors that lead to even more rooms. This computer code acts like a tiny explorer who wants to visit every single room in the treehouse to see the toys.
The explorer starts at the very top room and immediately looks at the toy inside. Once the explorer sees the toy, the explorer heads through the left door to see what is in the next room. After checking out that room, the explorer goes through the right door to find the rest of the rooms. The explorer keeps doing this over and over again until every single room has been visited. Each time the explorer finds a toy, the explorer writes down the name of the toy on a list so nothing gets forgotten. The process just repeats for every new room the explorer enters until there are no doors left to open.
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 | Rust | Go | TS | |||||||
| LeetcodeHelp | C++ | Python | Java | ||||||||||
| MemoryLimitExceeded | C++ | Python | |||||||||||
| Progiez | C++ | Python | Java | ||||||||||
| github | AdelDaniel | Dart | |||||||||||
| aylei | Rust | ||||||||||||
| begeekmyfriend | C | ||||||||||||
| black-shadows | C++ | ||||||||||||
| charles-wangkai | Java | ||||||||||||
| chenyanzhe | C++ | ||||||||||||
| Dijkstra-Edu | Java | ||||||||||||
| DimitrisJim | C | ||||||||||||
| everthis | JS | ||||||||||||
| fartem | Ruby | ||||||||||||
| fengvyi | C++ | ||||||||||||
| gaosq0604 | Python | ||||||||||||
| Garvit244 | Python | ||||||||||||
| halfrost | Go | ||||||||||||
| haoel | C++ | ||||||||||||
| JoshCrozier | JS | ||||||||||||
| keineahnung2345 | C++ | ||||||||||||
| Krazune | C++ | ||||||||||||
| lennylxx | C++ | ||||||||||||
| linouk23 | C++ | ||||||||||||
| lkwq007 | Python | ||||||||||||
| luangong | C++ | ||||||||||||
| muhammadfarhankt | Go | ||||||||||||
| pruthvikp | Python | ||||||||||||
| qiyuangong | Python | ||||||||||||
| ruoru | Rust | ||||||||||||
| shreymehul | C# | ||||||||||||
| suxrobGM | C# | ||||||||||||
| trung-hn | Python | ||||||||||||
| varunu28 | Java | ||||||||||||
| vli02 | C | ||||||||||||
| vthwang | Java | ||||||||||||
| wisdompeak | C++ | ||||||||||||
| XiaotaoGuo | C++ | ||||||||||||
| yuanliu666 | Kotlin | ||||||||||||
| YuriSpiridonov | Python | ||||||||||||
| zfang399 | C++ | ||||||||||||
| AlgoMonster | C++, Python, Java, TypeScript | ||||||||||||
| WalkCCC | C++, Python, Java | ||||||||||||
| leetcode.ca | C++, Go, Java, Python, Rust, TypeScript | ||||||||||||
| LeetcodeHelp | C++, Java, Python | ||||||||||||
| MemoryLimitExceeded | Python, C++ | ||||||||||||
| Progiez | C++, Java, Python | ||||||||||||
| AdelDaniel | Dart | ||||||||||||
| aylei | Rust | ||||||||||||
| begeekmyfriend | C | ||||||||||||
| black-shadows | C++, C++ | ||||||||||||
| charles-wangkai | Java | ||||||||||||
| chenyanzhe | C++ | ||||||||||||
| Dijkstra-Edu | Java | ||||||||||||
| DimitrisJim | C | ||||||||||||
| everthis | JavaScript | ||||||||||||
| fartem | Ruby | ||||||||||||
| fengvyi | C++ | ||||||||||||
| gaosq0604 | Python | ||||||||||||
| Garvit244 | Python | ||||||||||||
| halfrost | Go | ||||||||||||
| haoel | C++ | ||||||||||||
| JoshCrozier | JavaScript | ||||||||||||
| keineahnung2345 | C++ | ||||||||||||
| Krazune | C++ | ||||||||||||
| lennylxx | C++ | ||||||||||||
| linouk23 | C++ | ||||||||||||
| lkwq007 | Python | ||||||||||||
| luangong | C++ | ||||||||||||
| muhammadfarhankt | Go | ||||||||||||
| pruthvikp | Python | ||||||||||||
| qiyuangong | Python | ||||||||||||
| ruoru | Rust | ||||||||||||
| shreymehul | C# | ||||||||||||
| suxrobGM | C# | ||||||||||||
| trung-hn | Python | ||||||||||||
| varunu28 | Java | ||||||||||||
| vli02 | C | ||||||||||||
| vthwang | Java | ||||||||||||
| wisdompeak | C++ | ||||||||||||
| XiaotaoGuo | C++ | ||||||||||||
| yuanliu666 | Kotlin | ||||||||||||
| YuriSpiridonov | Python | ||||||||||||
| zfang399 | C++ |
Videos
Similar Problems
- problem 94: Binary Tree Inorder Traversal
- problem 255: Verify Preorder Sequence in Binary Search Tree
Solved On The Same Day
- 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 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