> For the complete documentation index, see [llms.txt](https://jimmylin1991.gitbook.io/practice-of-algorithm-problems/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://jimmylin1991.gitbook.io/practice-of-algorithm-problems/tree/114.-flatten-binary-tree-to-linked-list.md).

# 114. Flatten Binary Tree to Linked List

Given a binary tree, flatten it to a linked list in-place.

For example, given the following tree:

```
    1
   / \
  2   5
 / \   \
3   4   6
```

The flattened tree should look like:

```
1
 \
  2
   \
    3
     \
      4
       \
        5
         \
          6
```

{% hint style="info" %}
把左邊的節點一個一個搬到右邊的subtree上。
{% endhint %}

```cpp
// Iteration
void flatten(TreeNode* root) { // time: O(n); space: O(1)
    TreeNode* cur = root;
    while (cur) {
        if (cur->left) {
            TreeNode* pre = cur->left;
            // Find the prenode of the current node
            while (pre->right) {
                pre = pre->right;
            }
            // Link the prenode to the current node's right subtree
            pre->right = cur->right;
            // Replace the current node's right subtree with the current node's left subtree
            cur->right = cur->left;
            cur->left = nullptr;
        }
        cur = cur->right;
    }
}
```

```cpp
// Recursion
void helper(TreeNode* root, TreeNode*& prev) {
    if (!root) return;
    helper(root->right, prev);
    helper(root->left, prev);
    root->right = prev;
    root->left = nullptr;
    prev = root;
}
void flatten(TreeNode* root) { // time: O(n); space: O(n)
    TreeNode* prev = nullptr;
    helper(root, prev);
}
```
