Preorder binary search tree is increasing sequence
First, we can preorder binary search tree, digital depositvector
The new tree is from vectorthe end of the beginning, from the end of the current element to elementsum
Trans inorder traversal of the binary search tree is a descending sequence
Anti inorder traversal binary search tree, the current equal to the current elementsum
Third, the problem-solving Code
Preorder solution
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;}};
Anti preorder Solution
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;}};