```
class Solution {
public:
void flatten(TreeNode* root) {
if (root == NULL)
return;
if (root->right == NULL && root->left == NULL)
return;
if (root->right) {
flatten(root->right);
}
if (root->left) {
flatten(root->left);
}
if (root->right && root->left) {
TreeNode *lastRightFromLeftNode = root->left;
while (lastRightFromLeftNode->right) {
lastRightFromLeftNode = lastRightFromLeftNode->right;
}
lastRightFromLeftNode->right = root->right;
}
if (root->left) {
root->right = root->left;
root->left = NULL;
}
}
};
```