Problem 144

Abstract / Summary

Given the root of a binary tree return the preorder traversal of its nodes as a list of values

Note

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

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)
9 lines | 299 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 76% (3+ million submissions).

Typical patterns to solve this problem:
  • Binary Tree
  • 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 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.

written by openai gpt

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.

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 | μ = 7.59 | σ = 1.39

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 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++
58 links | 43 authors | 12 languages

Videos

These are a few popular YouTube videos for this problem:
YouTube video 'Binary Tree Preorder Traversal (Iterative) - Leetcode 144 - Python'
NeetCodeIO 10 mins
Binary Tree Preorder Traversal (Iterative) - Leetcode 144 - Python
YouTube video 'Binary Tree Preorder Traversal - LeetCode 144 Python'
Deepti Talesra 14 mins
Binary Tree Preorder Traversal - LeetCode 144 Python
YouTube video 'LeetCode 144. Binary Tree Preorder Traversal ITERATIVELY - Interview Prep Ep 76'
Fisher Coder 13 mins
LeetCode 144. Binary Tree Preorder Traversal ITERATIVELY - Interview Prep Ep 76
YouTube video '[Java] Leetcode 144. Binary Tree Preorder Traversal (Iteratively & Recursively) [Binary Tree #1]'
Eric Programming 9 mins
[Java] Leetcode 144. Binary Tree Preorder Traversal (Iteratively & Recursively) [Binary Tree #1]
YouTube video 'LeetCode 144. Binary Tree Preorder Traversal RECURSIVELY - Interview Prep Ep 67'
Fisher Coder 7 mins
LeetCode 144. Binary Tree Preorder Traversal RECURSIVELY - Interview Prep Ep 67
YouTube video 'Leetcode 144. Binary Tree Preorder Traversal'
Fraz 12 mins
Leetcode 144. Binary Tree Preorder Traversal
YouTube video 'Binary Tree Preorder Traversal - (Microsoft, Walmart, Flipkart, Amazon) : Explanation ➕ Live Coding'
codestorywithMIK 3 mins
Binary Tree Preorder Traversal - (Microsoft, Walmart, Flipkart, Amazon) : Explanation ➕ Live Coding
YouTube video '144. Binary Tree Preorder Traversal | Both Recursive & Iterative Solution | Vishal Rajput'
Vishal Rajput 12 mins
144. Binary Tree Preorder Traversal | Both Recursive & Iterative Solution | Vishal Rajput
YouTube video 'Iterative Preorder Traversal Of Binary Tree In Hindi ( Leetcode 144 )'
Engineering Digest 9 mins
Iterative Preorder Traversal Of Binary Tree In Hindi ( Leetcode 144 )
YouTube video 'Leetcode 144 Binary Tree Preorder Traversal (Java)'
TheAnalyticGuy 3 mins
Leetcode 144 Binary Tree Preorder Traversal (Java)
YouTube video 'Binary Tree Preorder Traversal - Iterative / Recursive - Python'
CheatCode Ninja 5 mins
Binary Tree Preorder Traversal - Iterative / Recursive - Python
YouTube video '144. Binary Tree Preorder Traversal Java Solution'
Code with Carter 8 mins
144. Binary Tree Preorder Traversal Java Solution
YouTube video 'Binary Tree PreOrder Traversal - LeetCode 144 - Malayalam | PreOrder, InOrder, PostOrder Explained'
WeCode Community 14 mins
Binary Tree PreOrder Traversal - LeetCode 144 - Malayalam | PreOrder, InOrder, PostOrder Explained
YouTube video 'Daily Leetcode #1014: Jan 09, 2023 - 144. Binary Tree Preorder Traversal'
Programming Live with Larry 9 mins
Daily Leetcode #1014: Jan 09, 2023 - 144. Binary Tree Preorder Traversal
YouTube video '144. Binary Tree Preorder Traversal | JavaScript | Recursion | O(n) TC | LeetCode Daily Challenge'
LeetCodeWithMonu 7 mins
144. Binary Tree Preorder Traversal | JavaScript | Recursion | O(n) TC | LeetCode Daily Challenge
YouTube video '144. Binary Tree Preorder Traversal || Leetcode || Coding with Explanation'
TechWithSaumya 7 mins
144. Binary Tree Preorder Traversal || Leetcode || Coding with Explanation
YouTube video 'Binary Tree Preorder Traversal - Google Interview Questions - LeetCode 144 Solution - C++'
nexTRIE 4 mins
Binary Tree Preorder Traversal - Google Interview Questions - LeetCode 144 Solution - C++
YouTube video '144 || Binary Tree Preorder Traversal || Leetcode Daily Challenge'
CodeFreaks 4 mins
144 || Binary Tree Preorder Traversal || Leetcode Daily Challenge
YouTube video 'How To Solve "144  Binary Tree Preorder Traversal" on LeetCode - JavaScript'
Becoming A Better Dev (with David) 6 mins
How To Solve "144 Binary Tree Preorder Traversal" on LeetCode - JavaScript
YouTube video 'Leetcode 144: Binary Tree Preorder Traversal'
Algorithms Casts 5 mins
Leetcode 144: Binary Tree Preorder Traversal
20 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