```
class Solution {
public:
TreeNode *p;
void dfs(TreeNode *root, TreeNode *&p) {
TreeNode *left = root->left;
TreeNode *right = root->right;
if (p == NULL) {
p = root;
p->left = p->right = NULL;
} else {
p->right = root;
p = p->right;
p->left = p->right = NULL;
}
if (left)
dfs(left, p);
if (right)
dfs(right, p);
}
void flatten(TreeNode *root) {
if (!root)
return;
p = NULL;
dfs(root, p);
return;
}
};
```