Flatten Binary Tree to Linked List
LeetCode 114 • Medium • Trees • Anduril
Flatten a binary tree to a right-linked list in preorder, in-place. Demo: 1→2→3→4→5.
TimeO(n)visit each node once
SpaceO(h)explicit stack
stack—
prev—
node—
spine—
Ready
Press Play to walk the algorithm.
TimeO(n)visit each node once
SpaceO(h)recursion stack
Ready
Press Play to walk the algorithm.
flatten(root) — mutate tree so it becomes a right-only linked list (preorder). Iterative stack: push right then left, rewire prev.
PATTERN ▸ stack preorder + prev rewire O(n) · O(h)
① EDGE
if not root: return
② INIT
stack = [root]
prev = None
③ LOOP (preorder)
node = stack.pop()
push right first, then left (so left is next)
④ REWIRE
if prev: prev.right = node; prev.left = None
prev = node
your implementation
flatten(root) — mutate tree so it becomes a right-only linked list (preorder). Recurse children, then splice left onto right.
PATTERN ▸ postorder splice
① flatten(right); flatten(left)
② if left: rightmost(left).right = root.right
root.right = root.left; root.left = None
your implementation