LeetCode 114: Flatten Binary Tree to Linked List — Python Solution

LeetCode 114: Flatten Binary Tree to Linked List is a Medium binary tree general problem. This Python walkthrough develops a reverse preorder threading solution, ties every code decision to a concrete invariant, and includes the regression check used before publication.

This independent guide paraphrases the task rather than reproducing LeetCode’s prompt. Use the official page for the exact statement, examples, constraints, and submission runner.

DifficultyMedium
TopicBinary Tree General
Reusable patternreverse preorder threading
ComplexityO(n) time and O(h) recursion space

Recognizing the pattern

Tree recursion works when the return value has one precise meaning for every subtree; the parent can then combine child results locally.

For this problem specifically, traverse right then left while keeping the previously processed node, and make each node point right to that previous node with left cleared. The invariant worth writing beside the code is: prev is the already flattened successor sequence for the current node in preorder.

Step-by-step algorithm

  1. Identify the input state consumed by flatten(root) and initialize the data required by the reverse preorder threading pattern.
  2. Traverse right then left while keeping the previously processed node, and make each node point right to that previous node with left cleared.
  3. After each update, verify the page’s central invariant: prev is the already flattened successor sequence for the current node in preorder.
  4. Finish only after the boundary behavior is covered: Every left pointer must finish null.

Python solution

LeetCode supplies the list, tree, or graph node class referenced by this method. The downloadable test suite includes compatible local node definitions so the implementation can also run outside the judge.

class Solution:
    def flatten(self, root):
        previous = None
        def visit(node):
            nonlocal previous
            if not node:
                return
            visit(node.right)
            visit(node.left)
            node.right = previous
            node.left = None
            previous = node
        visit(root)

Reading the implementation

The main entry point is flatten(root). The named working state includes previous; those variables make the reverse preorder threading state visible instead of hiding it in incidental control flow.

The method expresses the transformation directly without a general traversal loop. In concrete terms, traverse right then left while keeping the previously processed node, and make each node point right to that previous node with left cleared.

Correctness argument

Base case. Empty or terminal subproblems return a result that already satisfies the claim for that smallest state.

Inductive step. Traverse right then left while keeping the previously processed node, and make each node point right to that previous node with left cleared. Assuming child or smaller states are correct, the current call combines only results allowed by the problem, so prev is the already flattened successor sequence for the current node in preorder.

Conclusion. Every recursive call reduces the remaining state. The base cases terminate, and induction carries the invariant back to the original input, establishing the returned answer.

Complexity and trade-offs

O(n) time and O(h) recursion space. The auxiliary-space figure excludes the returned output unless the output itself is the structure being built.

An explicit stack avoids recursion-depth limits, but it must carry the same state that recursive call frames provide automatically. That comparison is useful in an interview because it explains why the final implementation is preferable, not merely that it passes.

Regression check

The published implementation belongs to a 100-problem suite that is compiled and exercised behaviorally before deployment.

One reference assertion from that suite is shown below. It targets the normal path while the edge conditions in the next section cover the failure-prone boundaries.

flat=tree([1,2,5,3,4,None,6]); Solution().flatten(flat); assert right_listed(flat)==[1,2,3,4,5,6]

Common mistakes and edge cases

  • Problem-specific boundary: Every left pointer must finish null.
  • Pattern-level pitfall: Write the empty-subtree result first and keep returned subtree information separate from any global answer updated at a node.
  • Invariant check: after every update, confirm that prev is the already flattened successor sequence for the current node in preorder.

Interview review checklist

  • Explain why reverse preorder threading matches the structure of this input.
  • State the invariant in one sentence before tracing code: prev is the already flattened successor sequence for the current node in preorder.
  • Derive O(n) time and O(h) recursion space from how many times each element or state is visited.
  • Test the boundary explicitly: Every left pointer must finish null.

Browse the searchable 100 LeetCode Python Solutions hub. Previous: 117. Populating Next Right Pointers in Each Node II · Next: 112. Path Sum