题目来源【Leetcode】
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.
Example:
Input: The root of a Binary Search Tree like this:
5
/ \
2 13Output: The root of a Greater Tree like this:
18
/ \
20 13
这道题是通过中序遍历来使每一个节点加上之前比他大的那个数
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
void f(TreeNode*root,int& n){
if(root == NULL)return;
f(root->right,n);
root->val += n;
n = root->val;
f(root->left,n);
}
class Solution {
public:
TreeNode* convertBST(TreeNode* root) {
int n = 0;
f(root,n);
return root;
}
};