Flatten Binary Tree To Linked List Problem
Description
LeetCode Problem 114.
Given the root of a binary tree, flatten the tree into a "linked list":
- The "linked list" should use the same TreeNode class where the right child pointer points to the next node in the list and the left child pointer is always null.
- The "linked list" should be in the same order as a pre-order traversal of the binary tree.
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 = []
Output: []
Example 3:
Input: root = [0]
Output: [0]
Constraints:
- The number of nodes in the tree is in the range [0, 2000].
- -100 <= Node.val <= 100
Solution
Approach: Rewire Each Left Subtree (O(1) Space)
Collecting the nodes in preorder into a list and then relinking them is easy, but it needs O(n) extra space. We can instead rewire the tree in place as we walk down the right pointers.
Look at a node with a left subtree. In preorder, the node is followed by its whole left subtree and then its whole right subtree. The last node of the left subtree in preorder is its rightmost node: keep following right from the left child until there is none. So the right subtree must be attached right after that node.
Walk with node starting at root:
- If
node.leftexists:- Find
rightmost, the rightmost node ofnode.left. - Set
rightmost.right = node.right, so the right subtree hangs after the left one. - Move the left subtree over:
node.right = node.left, thennode.left = null.
- Find
- Move to
node.rightand repeat until it isnull.
1 1 1
/ \ \ \
2 5 -> 2 ... 2
/ \ \ / \ \
3 4 6 3 4 3 -> 4 -> 5 -> 6
\
5
\
6
Do not forget node.left = null. Without it the old left links stay in place, and the result is not a list (every left pointer must be null).
Finding rightmost looks like it could make this quadratic, but it is not. Each search walks down a chain of right pointers inside the left subtree, and once that chain has been moved to the right it is never searched again, so each node is passed over a constant number of times in total.
Complexity: O(n) time, where n is the number of nodes, and O(1) extra space.
class Solution:
def flatten(self, root: Optional[TreeNode]) -> None:
"""
Do not return anything, modify root in-place instead.
"""
node = root
while node is not None:
if node.left is not None:
# In preorder, the right subtree comes right after the last node of the left subtree,
# which is the left subtree's rightmost node.
rightmost = node.left
while rightmost.right is not None:
rightmost = rightmost.right
rightmost.right = node.right
node.right = node.left # move the left subtree to the right
node.left = None
node = node.right
Now write it from memory
Close the write-up and solve it yourself against the tests.