We do this recursively.

for a node root, we flatten its left node and right node:

- Using tail to record the left node's linklist's tail
- Using tailtail to record the right node's linklist's tail

then we connect tail and root->right, root and root->left.

The code is below:

```
/**
* 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* dfs(TreeNode* root) {
if (!root) return NULL;
TreeNode* tail = dfs(root->left);
TreeNode* tailtail = dfs(root->right);
if (tail) {
tail->right = root->right;
root->right = root->left;
root->left = NULL;
}
return tailtail ? tailtail : (tail ? tail : root);
}
void flatten(TreeNode* root) {
if (!root) return;
dfs(root);
}
};
```