Skip to content
BytePatterns

Flatten a Tree Into a Chain

MediumTrees & BST#preorder#explicit-stack~25m

Problem

Given the root of a binary tree, rewire it in place into a chain that follows preorder: the root first, then its left subtree, then its right subtree. In the chain every node's left link is None and its right link points to the next node in preorder. Only links may change; no new nodes may be created.

Examples

Input:  tree = 7, left 3 (children 1 and 5), right 9 (left child 8)
Output: chain 7 -> 3 -> 1 -> 5 -> 9 -> 8
Why:    that is the preorder of the tree
Input:  tree = 4, left 2, whose left is 1
Output: chain 4 -> 2 -> 1
Why:    the left spine becomes a right spine
Input:  tree = empty
Output: empty chain
Why:    edge case, there is nothing to rewire

Hints

0 / 3

Stuck on the idea rather than the code? Tree Traversals covers it.