Given a Binary Search Tree (BST), convert it to a Greater Tree such that every key of the original BST is changed to the original key plus sum of all keys greater than the original key in BST.
思路:中序遍历
1右节点->s
2根节点+s->s
3左节点+s
/**
* Definition of TreeNode:
* class TreeNode {
* public:
* int val;
* TreeNode *left, *right;
* TreeNode(int val) {
* this->val = val;
* this->left = this->right = NULL;
* }
* }
*/
class Solution {
public:
/**
* @param root the root of binary tree
* @return the new root
*/
int sum =0;
TreeNode* convertBST(TreeNode* root) {
// Write your code here
if(root==NULL)
return NULL;
convertBST(root->right);
int t=root->val;
root->val=sum+t;
sum=sum+t;
convertBST(root->left);
return root;
}
};