Problem Description
Given the root of a binary tree, transform the tree into a "linked list" in-place following the pre-order traversal. In the resulting tree, every node’s left pointer should be null and the right pointer should point to the next node in the pre-order sequence.
Key Insights
- The goal is to rearrange the tree without using extra space for new nodes or data structures.
- A pre-order traversal order must be maintained, meaning the current node is processed before its left and right children.
- One in-place solution involves iterating over nodes, finding the rightmost node in the left subtree (if it exists), attaching the original right subtree to this node, then moving the left subtree to the right.
- Using an iterative approach can achieve O(1) extra space, while a recursive solution may use stack space proportional to the tree height.
Space and Time Complexity
Time Complexity: O(n) where n is the number of nodes (each node is processed a constant number of times).
Space Complexity: O(1) extra space in the iterative solution (ignoring recursion stack in the recursive approach).
Solution
We use an iterative approach to flatten the tree. The idea is to start from the root and for each node:
- If a left child exists, locate the rightmost node of the left subtree.
- Attach the node’s existing right subtree to the right pointer of this rightmost node.
- Move the left subtree to the right pointer of the current node and set the left pointer to null.
- Move to the next node (which is now the right child) and repeat until all nodes have been processed.
This approach effectively re-links all nodes following a pre-order traversal and avoids the overhead of extra space (aside from loop variables).