```
class Solution {
public:
TreeNode* flattenHelper(TreeNode *root){
if(root->left == NULL and root->right == NULL){
return root;
}
else if(root->left == NULL and root->right != NULL){
return flattenHelper(root->right);
}else if(root->left != NULL and root->right == NULL){
root->right = root->left;
root->left = NULL;
return flattenHelper(root->right);
}else{
TreeNode * leftLast = flattenHelper(root->left);
TreeNode * rightLast = flattenHelper(root->right);
TreeNode * rightFirst = root->right;
root->right = root->left;
leftLast->right = rightFirst;
root->left = NULL;
return rightLast;
}
}
void flatten(TreeNode* root) {
if(root == NULL) return;
else flattenHelper(root);
}
};
```