考察树的中序遍历。
BST是左子树小于右子树。
中序便利会输出他的从达到小的顺序。
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class Solution {
public:
int sum=0,now=0;
void f(TreeNode* root){
if(root==NULL) return ;
f(root->left);
sum+=root->val;
//cout<<root->val<<endl;
f(root->right);
}
void f1(TreeNode* root){
if(root==NULL) return ;
f1(root->left);
now+=root->val;
root->val+=(sum-now);
f1(root->right);
}
TreeNode* convertBST(TreeNode* root) {
f(root);
//cout<<"s"<<sum<<endl;
f1(root);
return root;
}
};