sagelearnai

Flatten Binary Tree to Linked List

Difficulty: Medium · Pattern: Trees & BST · LeetCode #114

Flatten a binary tree in place into a "linked list" that uses the right pointers, in preorder, with every left pointer set to null. Return nothing; the tests inspect root afterwards.

Examples

text
    1
   / \
  2   5        →   1 → 2 → 3 → 4 → 5 → 6   (all via .right)
 / \   \
3   4   6
[1,2,5,3,4,null,6]  →  [1,null,2,null,3,null,4,null,5,null,6]

Hints

  1. In preorder, a node's right subtree comes right after the last node of its left subtree. That's the rightmost node of the left subtree.
  2. Can you wire that up without recursion or a stack?

Approach

O(1)-space splice (Morris-style):

text
cur = root
while cur:
    if cur.left:
        pre = cur.left
        while pre.right: pre = pre.right   # rightmost node of the left subtree
        pre.right = cur.right              # hang the right subtree after it
        cur.right = cur.left               # move the left subtree to the right
        cur.left = None
    cur = cur.right

Each edge is walked a constant number of times overall, so the total is O(n).

Recursive alternative: reverse preorder (right, left, node) with a prev pointer: node.right = prev; node.left = None; prev = node.

Complexity

Time: O(n). Space: O(1).

Python solution
def flatten(root):
    cur = root
    while cur:
        if cur.left:
            pre = cur.left
            while pre.right:
                pre = pre.right
            pre.right = cur.right
            cur.right = cur.left
            cur.left = None
        cur = cur.right
JavaScript solution
function flatten(root) {
  let cur = root;
  while (cur) {
    if (cur.left) {
      let pre = cur.left;
      while (pre.right) pre = pre.right;
      pre.right = cur.right;
      cur.right = cur.left;
      cur.left = null;
    }
    cur = cur.right;
  }
}