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 rightleft
Example 1
Output: [1, null, 2, null, 3, null, 4, null, 5, null, 6]
Example 2
Output: [0]
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 leftright
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.
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 ArrayListrightleft
Java Solution
The method flatten
- First, set a variable
tonode . A loop walks the chain whileroot is not null.node - If
has a left child, find the rightmost node of its left subtree. A variablenode starts attail , and an inner loop moves it right untilnode.left is null.tail.right - Then change three pointers:
hangs the old right subtree aftertail.right = node.right ,tail moves the left subtree to the right, andnode.right = node.left clears the left side.node.left = null - Finally,
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.node = node.right
Around the method sit a small TreeNodebuildshow
The main
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:
[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 []root
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]
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
andnode , with no list, stack or recursion, and every change reuses a pointer the tree already has.tail
Preorder and the other orders for walking a tree are covered in