SDE & MLE Prep

114. Flatten Binary Tree to Linked List

Problem

Flatten a binary tree in place into a "linked list" that follows preorder: each node's right points to the next node in preorder and every left is null.

Example: [1,2,5,3,4,null,6] → 1 → 2 → 3 → 4 → 5 → 6 along right pointers

Constraints: follow-up: O(1) extra space.

For each node with a left child: find the rightmost node of the left subtree, hook the right subtree there, move left to right. Walk right. O(1) space (Morris-style).

    1            1
   / \            \
  2   5    ->      2
 / \   \            \
3   4   6            3 - 4 - 5 - 6

Complexity: O(n) time, O(1) space.

class Solution:
    def flatten(self, root: Optional[TreeNode]) -> None:
        cur = root
        while cur:
            if cur.left:
                p = cur.left
                while p.right:
                    p = p.right
                p.right = cur.right
                cur.right, cur.left = cur.left, None
            cur = cur.right