# 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);
}
```


---

# Agent Instructions: Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://jimmylin1991.gitbook.io/practice-of-algorithm-problems/tree/114.-flatten-binary-tree-to-linked-list.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
