Problem 114

Abstract / Summary

Transform a binary tree into a singly linked list by moving all nodes to the right side in preorder order.

Note

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

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
24 lines | 618 bytes | submitted August 15, 2023 | GitHub   tab size 4 | low complexity

Difficulty

This problem is ranked as
easy medium hard

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
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 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.

written by openai gpt

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.

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 = 5 | μ = 4.85 | σ = 1.94

Complexity Analysis

not analyzed yet

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 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++
55 links | 39 authors | 11 languages

Videos

These are a few popular YouTube videos for this problem:
YouTube video 'Flatten Binary Tree to Linked List - Leetcode 114 - Python'
NeetCode 15 mins
Flatten Binary Tree to Linked List - Leetcode 114 - Python
YouTube video 'Flatten Binary Tree to Linked List | Live Coding with Explanation | Leetcode - 114'
Algorithms Made Easy 13 mins
Flatten Binary Tree to Linked List | Live Coding with Explanation | Leetcode - 114
YouTube video 'Flatten Binary Tree to Linked List | Leetcode #114'
Techdose 16 mins
Flatten Binary Tree to Linked List | Leetcode #114
YouTube video 'LeetCode - 114. Flatten Binary Tree to Linked List | Day 14 May Challenge'
Aditya Mahajan 15 mins
LeetCode - 114. Flatten Binary Tree to Linked List | Day 14 May Challenge
YouTube video 'Flatten Binary Tree to Linked List | Leetcode 114 | Live coding session | Coding Interviews | May 14'
Coding Decoded 9 mins
Flatten Binary Tree to Linked List | Leetcode 114 | Live coding session | Coding Interviews | May 14
YouTube video 'Flatten Binary Tree to Linked List | LeetCode 114 | Coders Camp'
Coders Camp 8 mins
Flatten Binary Tree to Linked List | LeetCode 114 | Coders Camp
YouTube video 'Daily Leetcode #848: Jul 27, 2022 - 114. Flatten Binary Tree to Linked List'
Programming Live with Larry 46 mins
Daily Leetcode #848: Jul 27, 2022 - 114. Flatten Binary Tree to Linked List
YouTube video 'Flatten binary tree to linked list || C++ || GFG Daily Problem'
CodeFreaks 17 mins
Flatten binary tree to linked list || C++ || GFG Daily Problem
YouTube video 'Leetcode 114 - Flatten Binary Tree to Linked List (JAVA, Solution Explain!)'
LC Bear 7 mins
Leetcode 114 - Flatten Binary Tree to Linked List (JAVA, Solution Explain!)
YouTube video 'Leetcode 114 - Flatten Binary Tree to Linked List (O(1) Java Solution)'
LC Bear 5 mins
Leetcode 114 - Flatten Binary Tree to Linked List (O(1) Java Solution)
YouTube video '114. Flatten Binary Tree to Linked List | Leetcode | Binary Tree | DSA'
Coding with Tamilarasan 12 mins
114. Flatten Binary Tree to Linked List | Leetcode | Binary Tree | DSA
YouTube video 'Daily Leetcode #409: May 14, 2021 - 114. Flatten Binary Tree to Linked List'
Programming Live with Larry 17 mins
Daily Leetcode #409: May 14, 2021 - 114. Flatten Binary Tree to Linked List
YouTube video 'Flatten Binary Tree to Linked List || Leetcode Daily Challenge'
CodeFreaks 6 mins
Flatten Binary Tree to Linked List || Leetcode Daily Challenge
YouTube video '114. Flatten Binary Tree to Linked List || Leetcode Medium || Tree'
Komal Pal 16 mins
114. Flatten Binary Tree to Linked List || Leetcode Medium || Tree
YouTube video 'LeetCode 114 | Flatten Binary Tree to Linked List | Recursion | Java'
Sleepy Cracker 6 mins
LeetCode 114 | Flatten Binary Tree to Linked List | Recursion | Java
YouTube video 'Day 232: LeetCode Problem 114. Flatten Binary Tree to Linked List - Swift'
iOSxBank 9 mins
Day 232: LeetCode Problem 114. Flatten Binary Tree to Linked List - Swift
YouTube video '114. Flatten Binary Tree to Linked List | Leetcode | Python'
Abdullah Arshed 3 mins
114. Flatten Binary Tree to Linked List | Leetcode | Python
YouTube video 'Leetcode 114. Flatten Binary Tree to Linked List - 4 solution-formats with recursion and iteration'
Code-Yao 24 mins
Leetcode 114. Flatten Binary Tree to Linked List - 4 solution-formats with recursion and iteration
18 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   August 15, 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