classSolution{public:
TreeNode*bstToGst(TreeNode* root){if(!root)return root;
vector<int> vec;
stack<TreeNode*>s;auto p = root;while(!s.empty()|| p){while(p){
s.push(p);
p = p->left;}if(!s.empty()){
p = s.top();
s.pop();
vec.push_back(p->val);
p = p->right;}}int sum =0;for(auto i = vec.rbegin(); i != vec.rend(); i++){
sum +=*i;*i = sum;}int counter =0;
p = root;while(!s.empty()|| p){while(p){
s.push(p);
p = p->left;}if(!s.empty()){
p = s.top();
s.pop();//vec.push_back(p->val);
p->val = vec[counter++];
p = p->right;}}return root;}};
反中序遍历解法
classSolution{public:int sum =0;public:
TreeNode*bstToGst(TreeNode* root){if(root){
root->right =bstToGst(root->right);
sum += root->val;
root->val = sum;
root->left =bstToGst(root->left);}return root;}};