Binary Tree · Pointer Rewiring

Flatten Binary Tree to Linked List

Rewire pointers in-place so the tree becomes a preorder right-only chain.

Key concepts at a glance — for those who already know the basics.

Problem Statement

Flatten the tree in-place to a linked list using right pointers in preorder sequence.

[1,2,5,3,4,null,6] -> 1 -> 2 -> 3 -> 4 -> 5 -> 6

01 · Before/After Diagram

Before125346flattenAfter (right-only chain)123456

02 · Iterative Rewiring Steps

  1. If current.left exists, find predecessor: rightmost node of left subtree.
  2. Connect predecessor.right to current.right.
  3. Move current.left to current.right.
  4. Set current.left = null and advance current = current.right.

03 · Quick Trace Grid

Step
Current
Action
Chain
1
1
Find rightmost of left subtree (node 4), connect 4.right -> 5
1 -> 2 -> 3 -> 4 -> 5 -> 6
2
1
Move left subtree to right, set 1.left = null
1 -> 2 -> 3 -> 4 -> 5 -> 6
3
2
Left absent, move ahead
1 -> 2 -> 3 -> 4 -> 5 -> 6
4
3
Left absent, move ahead
1 -> 2 -> 3 -> 4 -> 5 -> 6
5
4
Left absent, move ahead
1 -> 2 -> 3 -> 4 -> 5 -> 6

04 · Code

def flatten(root):
    cur = root
    while cur:
        if cur.left:
            pred = cur.left
            while pred.right:
                pred = pred.right
            pred.right = cur.right
            cur.right = cur.left
            cur.left = None
        cur = cur.right

05 · Complexity

Time O(n)

Each node is rewired once across traversal.

Extra Space O(1)

No recursion stack in iterative method.

Ready to see it in action?

Step through the visualizer to watch the algorithm state update live.

Open Visualizer