--- tags: leetcode --- # [114. Flatten Binary Tree to Linked List](https://leetcode.com/problems/flatten-binary-tree-to-linked-list/) --- # My Solution ## The Key Idea for Solving This Coding Question Use Morris traversal to solve this coding question. ## C++ Code ```cpp= /** * Definition for a binary tree node. * struct TreeNode { * int val; * TreeNode *left; * TreeNode *right; * TreeNode() : val(0), left(nullptr), right(nullptr) {} * TreeNode(int x) : val(x), left(nullptr), right(nullptr) {} * TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {} * }; */ class Solution { public: void flatten(TreeNode *root) { while (root != nullptr) { if (root->left != nullptr) { TreeNode *x = root->left; while (x->right != nullptr) { x = x->right; } x->right = root->right; root->right = root->left; root->left = nullptr; root = root->right; } else { root = root->right; } } } }; ``` ### Time Complexity $O(n)$ * $n$ is the number of nodes in the binary tree. ### Space Complexity $O(1)$ # Miscellaneous <!-- # Test Cases ``` [1,2,5,3,4,null,6] ``` ``` [] ``` ``` [0] ``` ``` [5,4,8,11,null,13,4,7,2,null,null,5,1] ``` ``` [5,4,8,11,null,13,4,7,2,null,null,null,1] ``` ``` [1,2] ``` ``` [1,null,2] ``` ``` [-2,6,null,0,-6] ``` -->