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