```
class Solution {
public:
TreeNode* convertBST(TreeNode* root) {
TreeNode *curr = root, *prev = NULL;
int sum = 0, index = 0;
while(curr)
{
if(curr->right == NULL)
{
curr->val += sum;
sum = curr->val;
++index;
curr = curr->left;
}
else
{
prev = curr->right;
while(prev->left && prev->left != curr) prev = prev->left;
if(prev->left == NULL)
{
prev->left = curr;
curr = curr->right;
}
else
{
prev->left = NULL;
++index;
curr->val += sum;
sum = curr->val;
curr = curr->left;
}
}
}
return root;
}
};
```