/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode() : val(0), left(nullptr), right(nullptr) {}
* TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
* TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
* };
*/
class Solution {
public:
int sum = 0;
TreeNode* convertBST(TreeNode* root) {
if(!root) return root;
convertBST(root->right);
sum += root->val;
root->val = sum;
convertBST(root->left);
return root;
}
};
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode() : val(0), left(nullptr), right(nullptr) {}
* TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
* TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
* };
*/
class Solution {
public:
vector<int> preSum = vector<int>(10010, 0);
int len = 0;
int ind = 0;
void inOrder(TreeNode* root) {
if(!root) return ;
inOrder(root->left);
preSum[len+1] = preSum[len] + root->val;
len++;
inOrder(root->right);
}
void convert(TreeNode* root) {
if(!root) return ;
convert(root->left);
root->val = preSum[len] - preSum[ind];
ind++;
convert(root->right);
}
TreeNode* convertBST(TreeNode* root) {
inOrder(root);
convert(root);
return root;
}
};