Flatten Binary Tree to Linked List

MediumTree recursionLeetCode 114 ↗World 3-16
0:00 / 0:00

Turn a tree into a right-leaning chain in preorder, in place. At each node, find the rightmost node of its left side, hang the right subtree there, swing the left side over to the right, and step on: O(n) time, O(1) space.

▼

The problem

LeetCode 114 (Medium). Given the root of a binary tree, flatten it in place into a "linked list": the same nodes, each node's right pointer leading to the next node in preorder, and every left pointer null.

Example 1 (LeetCode's) is the one on screen in scenes 2, 3, 6 and 7: [1,2,5,3,4,null,6] → [1,null,2,null,3,null,4,null,5,null,6].

TRY IT ON LEETCODE ▶

The solution

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

Transcript

Flatten Binary Tree to Linked List. Flatten a binary tree, in place, into one chain: each right pointer leads to the next node in preorder, and every left pointer is empty. Here, each node is a monkey, holding one below with each hand.

Here's our tree. One holds two and five. Two holds three and four, and five holds six. Preorder visits a node, then the left side, then the right side: one, two, three, four, five, six. So the chain hangs in that order, every left hand free.

The easy way walks the tree in preorder, copying each node into a list, then relinks them one by one. It works, but that list holds every node: order n extra space.

The key idea: rewire in place. Take a node with a left child. In preorder, the right side comes just after the last node of the left side. To find that node, start at the left child and keep going right. Hang the right side from it, swing the left side over to the right, and let go on the left. Then step right.

In code, a pointer starts at the root. If the node has a left child, a second pointer walks right to that side's end. Attach the right subtree there, move the left subtree to the right, and clear the left. Then move right.

Let's walk it. At one, the left side's rightmost is four. Five hangs from four, and two swings right. At two, the rightmost is three. Four hangs from three, and three swings right. Three, four, five and six have no left child, so we just step down. One chain, one through six.

The main pointer visits each node once, and the search never walks a link twice: order n time. With just two pointers, the extra space is order one. A recursion also works, but its stack costs the tree's height.

Find the rightmost, hang the right, swing the left. That's Flatten Binary Tree to Linked List.