Python 0114.py
class Solution:
def preorder(self, root):
if not root:
return []
return [ root.val ] + self.preorder(root.left) + self.preorder(root.right)
def flatten(self, root: Optional[TreeNode]) -> None:
if not root:
return root
flat = self.preorder(root)
prev = None
for i in flat:
if prev:
current = TreeNode(i, None, None)
prev.right = current
else:
current = root
current.left = current.right = None
prev = current
Difficulty
and has an acceptance rate of about 71% (2+ million submissions).
Typical patterns to solve this problem:
- Binary Tree
- Depth First Search
- Linked List
- 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 two public methods: preorder and flatten. The preorder method performs a depth-first traversal of a binary tree, returning a list of node values in root-left-right order. The flatten method transforms the original binary tree into a right-leaning linked list that follows the same preorder sequence, mutating the tree in place.
Preorder Traversal
The traversal begins with a guard clause that returns an empty list when the input node is None. This handles the edge case of an empty tree, ensuring that downstream code receives a well-defined empty collection rather than a None value.
if not root:
return []
When a node is present, the method constructs a new list by concatenating three parts: a singleton list containing the current node’s value, the result of recursively traversing the left subtree, and the result of recursively traversing the right subtree. This expression captures the classic preorder pattern without requiring auxiliary data structures.
return [ root.val ] + self.preorder(root.left) + self.preorder(root.right)
The recursion naturally terminates when leaf nodes are reached because their children are None, triggering the early return of an empty list.
Flattening the Tree
The flatten method also starts with a guard clause that exits early if the supplied root is None. In this scenario the method returns the None reference, preserving the original empty-tree state.
if not root:
return root
The core of the flattening process consists of two phases. First, the method obtains the preorder sequence of values by invoking the previously described preorder method.
flat = self.preorder(root)
The second phase iterates over the collected values, rebuilding the tree as a singly linked list that uses only right child pointers. A variable prev tracks the most recently processed node. For each value i in the preorder list, the code distinguishes between the first element and subsequent elements.
When processing the first element, the algorithm reuses the original root node as the starting point of the linked list. It explicitly clears both left and right references of this node, guaranteeing that the resulting structure conforms to the required right-only shape.
if prev:
current = TreeNode(i, None, None)
prev.right = current
else:
current = root
current.left = current.right = None
prev = current
For every later value, a fresh TreeNode instance is created with the current value and no children. The previous node’s right pointer is then directed to this new node, extending the chain. The prev reference is updated to point to the newly created node, preparing for the next iteration.
Edge Cases Handled
The implementation gracefully handles an empty input tree by returning an empty list from preorder and a None reference from flatten. For a tree consisting of a single node, the preorder list contains exactly one value. The flatten loop treats this as the first iteration, reusing the original node and clearing its children, resulting in a correctly flattened structure with no additional allocations.
Performance Optimizations
One notable optimization is the reuse of the original root node for the first element of the flattened list. By avoiding the creation of a new node for the head of the linked list, the code reduces memory allocation overhead and preserves the original object identity where it matters.
The concatenation pattern in the preorder method leverages Python’s list addition, which is efficient for the relatively small intermediate lists produced by each recursive call. This approach avoids the need for explicit list appends inside the recursion, keeping the code concise while still benefiting from Python’s internal optimizations for list concatenation.
The flattening loop processes the preorder list in a single pass, establishing the right-hand links without any nested loops or additional traversals. This linear progression ensures that the transformation runs in time proportional to the number of nodes, with each node being visited exactly once during the preorder generation and once during the reconstruction phase.
ELI5 - Simplified Explanation
Imagine a tree made of blocks where each block has a little tag with a number on it. Some blocks have branches leading to other blocks below them.
The first part of the code goes on a treasure hunt to find all the numbers. It starts at the very top block, writes down the number it sees, and then searches the left branch and the right branch to find every other number hiding in the tree. It keeps doing this over and over until it has a long, straight list of every single number found in the tree, kept in the exact order it visited them.
The second part of the code takes that long list of numbers and builds a new shape. Instead of a tree with branches, it makes a long, straight line where every block only points to the block directly below it like a tower. It loops through the list of numbers one by one, picking up a number, creating a new block for it, and attaching it to the bottom of the previous block. By the time it finishes the entire list, the tree has been transformed into a single, tidy line of blocks.
Code Quality
Complexity Analysis
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 | JS | Go | TS | |||||
| LeetcodeHelp | C++ | Python | Java | |||||||||
| MemoryLimitExceeded | C++ | Python | ||||||||||
| Progiez | C++ | Python | Java | |||||||||
| github | AdelDaniel | Dart | ||||||||||
| aylei | Rust | |||||||||||
| begeekmyfriend | C | |||||||||||
| BigEggStudy | C# | |||||||||||
| black-shadows | Python | |||||||||||
| charles-wangkai | Java | |||||||||||
| chenyanzhe | C++ | |||||||||||
| everthis | JS | |||||||||||
| fartem | Ruby | |||||||||||
| fengvyi | C++ | |||||||||||
| gaosq0604 | Python | |||||||||||
| halfrost | Go | |||||||||||
| haoel | C++ | |||||||||||
| JoshCrozier | JS | |||||||||||
| keineahnung2345 | C++ | |||||||||||
| lennylxx | C | |||||||||||
| linouk23 | C++ | |||||||||||
| lkwq007 | Python | |||||||||||
| luangong | C++ | |||||||||||
| MacJim | C++ | |||||||||||
| qiyuangong | Python | |||||||||||
| ruoru | Rust | |||||||||||
| shreymehul | C# | |||||||||||
| sonugiri1043 | C++ | |||||||||||
| suxrobGM | C# | |||||||||||
| trung-hn | Python | |||||||||||
| varunu28 | Java | |||||||||||
| vli02 | C | |||||||||||
| vthwang | Java | |||||||||||
| wisdompeak | C++ | |||||||||||
| XiaotaoGuo | C++ | |||||||||||
| YuriSpiridonov | Python | |||||||||||
| zfang399 | C++ | |||||||||||
| AlgoMonster | C++, Python, Java, TypeScript | |||||||||||
| WalkCCC | C++, Python, Java | |||||||||||
| leetcode.ca | C++, Go, Java, JavaScript, Python, Rust, TypeScript | |||||||||||
| LeetcodeHelp | C++, Java, Python | |||||||||||
| MemoryLimitExceeded | Python, C++ | |||||||||||
| Progiez | C++, Java, Python | |||||||||||
| AdelDaniel | Dart | |||||||||||
| aylei | Rust | |||||||||||
| begeekmyfriend | C | |||||||||||
| BigEggStudy | C# | |||||||||||
| black-shadows | Python, Python | |||||||||||
| charles-wangkai | Java | |||||||||||
| chenyanzhe | C++ | |||||||||||
| everthis | JavaScript | |||||||||||
| fartem | Ruby | |||||||||||
| fengvyi | C++ | |||||||||||
| gaosq0604 | Python | |||||||||||
| halfrost | Go | |||||||||||
| haoel | C++ | |||||||||||
| JoshCrozier | JavaScript | |||||||||||
| keineahnung2345 | C++ | |||||||||||
| lennylxx | C | |||||||||||
| linouk23 | C++ | |||||||||||
| lkwq007 | Python | |||||||||||
| luangong | C++ | |||||||||||
| MacJim | C++ | |||||||||||
| qiyuangong | Python | |||||||||||
| ruoru | Rust | |||||||||||
| shreymehul | C# | |||||||||||
| sonugiri1043 | C++ | |||||||||||
| suxrobGM | C# | |||||||||||
| trung-hn | Python | |||||||||||
| varunu28 | Java | |||||||||||
| vli02 | C | |||||||||||
| vthwang | Java | |||||||||||
| wisdompeak | C++ | |||||||||||
| XiaotaoGuo | C++ | |||||||||||
| YuriSpiridonov | Python | |||||||||||
| zfang399 | C++ |
Videos
Similar Problems
- problem 430: Flatten a Multilevel Doubly Linked List
- problem 1660: Correct a Binary Tree
Solved On The Same Day
- problem 112: Path Sum
- problem 409: Longest Palindrome
- problem 645: Set Mismatch
- problem 717: 1-bit and 2-bit Characters
- problem 2535: Difference Between Element Sum and Digit Sum of an Array
- problem 16: 3Sum Closest
- problem 24: Swap Nodes in Pairs
- problem 113: Path Sum II
- problem 116: Populating Next Right Pointers in Each Node
- problem 129: Sum Root to Leaf Numbers
- problem 131: Palindrome Partitioning
- problem 137: Single Number II
- problem 162: Find Peak Element
- problem 165: Compare Version Numbers
- problem 172: Factorial Trailing Zeroes
- problem 201: Bitwise AND of Numbers Range
- problem 204: Count Primes
- problem 402: Remove K Digits
- problem 430: Flatten a Multilevel Doubly Linked List
- problem 451: Sort Characters By Frequency
- problem 539: Minimum Time Difference
- problem 583: Delete Operation for Two Strings
- problem 633: Sum of Square Numbers
- problem 648: Replace Words
- problem 650: 2 Keys Keyboard
- problem 670: Maximum Swap
- problem 786: K-th Smallest Prime Fraction
- problem 2507: Smallest Value After Replacing With Sum of Prime Factors
- problem 2523: Closest Prime Numbers in Range
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