Flatten Binary Tree to Linked List

Medium

Topics
TreeDFSLinked ListStack

Given the root of a binary tree, flatten it into a linked list in place. The list must use the same TreeNode type, where right is the next node and left is always null.

The order must be the tree’s pre-order traversal. Return the values of the flattened list from head to tail.

Example 1

tree332244115566
list123456
head of the list
The small number above each node is its place in the flattened list: a node comes first, then everything in its left subtree, then everything in its right. The result has to be the same nodes relinked — every left null and right pointing at the next — not a fresh list of copies.
Tree given in level-order (breadth-first); null marks a missing child.
Input:  root = [1,2,5,3,4,null,6]
Output: [1,2,3,4,5,6]

Example 2

empty tree
Input:  root = []
Output: []

Example 3

tree01
list0
head of the list
Input:  root = [0]
Output: [0]

Constraints

  • 0 <= number of nodes <= 2000
  • -100 <= Node.val <= 100
Editorial — intuition, approach, complexity and pitfalls

Intuition

Pre-order visits a node, then everything in its left subtree, then everything in its right. So in the flattened list a node is followed by its whole left subtree, and the right subtree is pushed out to the very end of that run.

Rewiring one node is therefore local: put the left subtree on the right, and reattach the old right subtree to the tail of what was just moved. Doing that at every node, working down, flattens the tree without any extra storage.

Approach

  1. Start at the root and walk down the right spine.
  2. If the current node has no left child, step right and continue.
  3. Otherwise find the rightmost node of its left subtree — that is where the current right subtree has to be reattached, since it comes last in pre-order.
  4. Hang the current right subtree off that rightmost node, move the left subtree across to right, and clear left. Then step right into the subtree just moved.

Walkthrough

root = [1,2,5,3,4,null,6]

    1                 1
   / \                 \
  2   5       ->        2
 / \   \                 \
3  4    6                 3
                           \
                            4
                             \
                              5
                               \
                                6

At node 1: left subtree is 2-3-4, its rightmost node is 4.
Hang 5 off 4, move 2 to the right of 1, clear 1.left.

Complexity

  • Time — O(n): each edge is walked a constant number of times; every node is moved at most once.
  • Space — O(1): only a couple of pointers. A recursive version instead uses the call stack.

Common Pitfalls

  • Overwriting node.right before saving it loses the whole right subtree.
  • Forgetting to set left to null leaves a tree that happens to have the right order but is not a list.
  • The reattachment point is the rightmost node of the left subtree, not the left subtree’s root or its deepest node.

Full Solution — all languages

class TreeNode:
    def __init__(self, val=0, left=None, right=None):
        self.val = val
        self.left = left
        self.right = right

class Solution:
    def flatten(self, root):
        out = []

        def preorder(node):
            if not node:
                return
            out.append(node.val)
            preorder(node.left)
            preorder(node.right)

        preorder(root)
        return out
SensAI
Beta
Tap the mic to stop voice mode