Flatten Binary Tree to Linked List

Rewire a binary tree in place into one chain of right pointers that lists its nodes in preorder.

Given the root of a binary tree, rearrange its nodes in place, without creating new ones, so that they form a single chain. Each node's right pointer must lead to the next node of the chain, and every left pointer must be null. The chain lists the nodes in preorder: a node first, then all the nodes of its left subtree, then all the nodes of its right subtree. Trees are written row by row, with null for a missing child.

Example 1
Input: root = [1, 2, 5, 3, 4, null, 6]
Output: [1, null, 2, null, 3, null, 4, null, 5, null, 6]
Example 2
Input: root = [0]
Output: [0]
Solution

The Idea

Think of a book's table of contents. A chapter has sections, and a section has subsections, yet the contents page lists them all in one column: a heading, then everything under its first part, then everything under its next part. Flattening a tree is the same job, done with the tree's own pointers.

In Example 1, the root 1 has two children, 2 on its left and 5 on its right. Node 2 has the children 3 and 4, and node 5 has only a right child, 6. Read like a contents page, the tree gives 1, then the part under 2, which is 2, 3, 4, then the part under 5, which is 5, 6. The part that starts at a node's left child is its left subtree, and the part that starts at its right child is its right subtree. That reading order is called preorder. In the output, each null is the empty left child of the node just before it, so the output reads 1 to 6 down the right pointers.

Creating six new nodes in that order would be easy, but "in place" rules it out: only the existing left and right pointers may change. So where should node 1's right subtree, the part that starts at 5, be attached?

It must come right after the last node of 1's left subtree in preorder, which is 4. Finding 4 is simple: start at 2, the left child, and follow right pointers until there are none. The node where the right pointers run out is called the rightmost node of the left subtree. Look at the picture below.

Three panels. Before: at node 1, 4 is the rightmost node of the left subtree, and the right subtree 5, 6 must come after 4. After rewiring node 1: 1 points right to 2, 2 still has a left child 3 and a right child 4, and 4 points to 5, then 6. Flattened: the chain 1, 2, 3, 4, 5, 6, where every left pointer is null.

In the panel labelled "1. Before", 4 is the rightmost node of the left subtree, and the dashed arrow shows that the right subtree 5, 6 must come after 4. The panel "2. After rewiring node 1" shows three pointer changes. Node 4's right pointer now leads to 5, node 1's right pointer leads to 2, and 1 has no left child now.

The tree is not flat yet, because 2 still has a left child, 3. But 2 is now the next node on the right-pointer chain, so the same move at 2 fixes it. The rightmost node of 2's left subtree is 3, so 4 goes after 3, and 3 moves to 2's right. The panel "3. Flattened" shows the result.

So the whole job is one move, repeated: at each node of the chain, slide its left subtree in between the node and its right subtree, then walk on to the next node on the right.

Solution Approach

Turning that move into code means settling three things: where the right subtree goes, in which order the nodes are visited, and why the simpler way of collecting the nodes in a list first is not needed.

Where the right subtree goes

Which node should the right subtree hang from? From the rightmost node of the left subtree, found by following right pointers from the left child. In Example 1, that node, 4, is also the last one in preorder.

That is not always the case. In the tree [1, 2, 4, 3], node 1's left child 2 has only a left child, 3, so the rightmost node is 2 itself, while preorder ends with 3. Hanging 1's right subtree, 4, after 2 still works. When the walk reaches 2, the same move slides 3 in between 2 and 4, so 3 ends up before 4 as preorder requires.

The order of the visits

Which node comes next after a move? The node's right pointer now leads to its old left child, which is exactly the next node in preorder. So the walk only ever follows right pointers. Nodes moved into the chain may still have left children of their own, like 2 in the picture, and each is fixed when the walk reaches it. The walk never has to come back up the tree.

Collecting the nodes first

Is there a simpler way? A recursive preorder walk can collect every node in an ArrayList, and then a loop can point each node's right at the next one in the list and clear its left. It is correct and also visits each node once. But the list holds every node of the tree, and the recursion keeps one call open per level of the tree. The rewiring above needs no list and no recursion, only one variable for the current node and one for the search.

Java Solution

The method flatten works in these steps:

  1. First, set a variable node to root. A loop walks the chain while node is not null.
  2. If node has a left child, find the rightmost node of its left subtree. A variable tail starts at node.left, and an inner loop moves it right until tail.right is null.
  3. Then change three pointers: tail.right = node.right hangs the old right subtree after tail, node.right = node.left moves the left subtree to the right, and node.left = null clears the left side.
  4. Finally, node = node.right steps to the next node of the chain, which is the old left child whenever there was one. The method returns nothing, because the tree itself has changed.

Around the method sit a small TreeNode class, build, which makes a tree from the row-by-row form, and show, which prints a tree in that same form.

The main method runs both examples, an empty tree, a full tree of three rows, the tree [1, 2, 4, 3], a tree with only left children, and a tree that is already a chain.

Java
import java.util.ArrayDeque;
import java.util.ArrayList;
import java.util.Deque;
import java.util.List;

public class FlattenBinaryTreeToLinkedList {

    static class TreeNode {
        int val;
        TreeNode left, right;
        TreeNode(int val) { this.val = val; }
    }

    public static void flatten(TreeNode root) {
        TreeNode node = root;
        while (node != null) {
            if (node.left != null) {
                TreeNode tail = node.left;     // find the rightmost node on the left
                while (tail.right != null) {
                    tail = tail.right;
                }
                tail.right = node.right;       // hang the right subtree after it
                node.right = node.left;        // move the left subtree to the right
                node.left = null;
            }
            node = node.right;                 // go on down the chain
        }
    }

    // Builds a tree from its row-by-row form, with null for a missing child.
    static TreeNode build(Integer... vals) {
        if (vals.length == 0 || vals[0] == null) return null;
        TreeNode root = new TreeNode(vals[0]);
        Deque<TreeNode> queue = new ArrayDeque<>();
        queue.add(root);
        int i = 1;
        while (i < vals.length) {
            TreeNode parent = queue.poll();
            if (vals[i] != null) queue.add(parent.left = new TreeNode(vals[i]));
            i++;
            if (i < vals.length && vals[i] != null) {
                queue.add(parent.right = new TreeNode(vals[i]));
            }
            i++;
        }
        return root;
    }

    // Prints a tree in the same row-by-row form, without trailing nulls.
    static String show(TreeNode root) {
        List<Integer> out = new ArrayList<>();
        Deque<TreeNode> queue = new ArrayDeque<>();
        if (root != null) queue.add(root);
        out.add(root == null ? null : root.val);
        while (!queue.isEmpty()) {
            TreeNode n = queue.poll();
            for (TreeNode child : new TreeNode[] {n.left, n.right}) {
                out.add(child == null ? null : child.val);
                if (child != null) queue.add(child);
            }
        }
        while (!out.isEmpty() && out.get(out.size() - 1) == null) out.remove(out.size() - 1);
        return out.toString();
    }

    static void run(Integer... vals) {
        TreeNode root = build(vals);
        flatten(root);
        System.out.println(show(root));
    }

    public static void main(String[] args) {
        run(1, 2, 5, 3, 4, null, 6);           // Example 1
        run(0);                                // Example 2
        run();                                 // empty tree
        run(1, 2, 3, 4, 5, 6, 7);              // full tree of three rows
        run(1, 2, 4, 3);                       // node 2 is rightmost, with a left child
        run(1, 2, null, 3);                    // only left children
        run(1, null, 2, null, 3);              // already a chain
    }
}

Running it prints:

Output
[1, null, 2, null, 3, null, 4, null, 5, null, 6]
[0]
[]
[1, null, 2, null, 4, null, 5, null, 3, null, 6, null, 7]
[1, null, 2, null, 3, null, 4]
[1, null, 2, null, 3]
[1, null, 2, null, 3]

The first line matches Example 1, and its nulls show that every left pointer is empty. The empty tree gives [], because the loop never starts when root is null.

Look at the fourth line, from the full tree [1, 2, 3, 4, 5, 6, 7]. The chain reads 1, 2, 4, 5, 3, 6, 7, not 1 to 7: 4 and 5 sit under 2, so they come before 3, the root's right child. That is preorder, not row order.

The fifth line, [1, null, 2, null, 3, null, 4], comes from [1, 2, 4, 3], where the rightmost node of 1's left subtree is 2, not 3. The chain still puts 3 before 4, because the move at node 2 slid 3 into place. The sixth line turns [1, 2, null, 3], with only left children, into the same kind of chain. The last line is the tree that was already a chain, and it comes back unchanged.

Complexity

The work is the walk down the chain, plus the inner search for each rightmost node.

  • Time: O(n), because the walk steps onto each of the n nodes once, and each inner search runs along a right edge that then joins the chain, so no node is passed by two inner searches.
  • Space: O(1), because the method keeps only node and tail, with no list, stack or recursion, and every change reuses a pointer the tree already has.

Preorder and the other orders for walking a tree are covered in Trees Basics.