# 114. Flatten Binary Tree to Linked List

## 1.問題&#x20;

* 給予一個binary tree, 將他攤平成linked list (in-place)

![](https://901207480-files.gitbook.io/~/files/v0/b/gitbook-legacy-files/o/assets%2F-LGKoChvN9am4__HCIRK%2F-LOSWpDeKKzRSEn0doCN%2F-LOSk5QAoNQACytXtLdU%2F%E8%9E%A2%E5%B9%95%E5%BF%AB%E7%85%A7%202018-10-10%20%E4%B8%8B%E5%8D%887.32.44.png?alt=media\&token=1c0fa450-1667-450a-a81a-ed61427f89ef)

## 2.想法 <a href="#id-2-xiang-fa" id="id-2-xiang-fa"></a>

* 提問
  * 確認題意:  root是NULL是true或false?
* function header, parameter
* test input
* 說明想法
  * 1.用pre-order traversal整個tree, 用指標調整: 將下個node放到right
* 測試計算複雜度

## **3.程式碼** <a href="#id-3-cheng-shi" id="id-3-cheng-shi"></a>

* pre-order traversal

```
/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
 * };
 */
class Solution {
public:
    TreeNode* tmp = NULL;
    void flatten(TreeNode* root) {
        if (!root) {
            return;
        }
        if (tmp) {
            //將tmp的right child指向下個root
            tmp->left = NULL;
            tmp->right = root;
        }
        //將tmp指向下個root(移動)
        tmp = root;
        
        //儲存right
        TreeNode *right = root->right;
        //先整理left
        flatten(root->left);
        //整理right
        flatten(right); 
    }
};

```
