#114

Flatten Binary Tree to Linked List

Medium Morris-style rewiring

  1. Read
  2. Understand
  3. Hints
  4. Approach
  5. Solution
  6. Solved

?The problem

Flatten a binary tree into a "linked list" in place, using right pointers in preorder order and setting every left pointer to null.

This is a short summary in our own words. Read the full statement and examples on LeetCode: open problem ↗

◎Understanding

Really asking: turn the tree into a right-only chain in preorder.

Why this works: at each node with a left child, attach the right subtree to the end of the left subtree, then move the left subtree to the right.

Example: 1 (2 (3, 4), 5 (-, 6))

1 → 2 → 3 → 4 → 5 → 6

✦Hints open one at a time

↗Approach

</>Solution (Java)

!Common mistake

Forgetting to set left to null — the judge checks it.

Solve on LeetCode ↗
Complexity
  • Time: O(n).
  • Space: O(1).
Topic: Binary Trees
🎬 Episodes 53–60: video coming soon