1.描述:
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.
样例
2.思路:
Given a binary search Tree `{5,2,3}`:
5
/ \
2 13
Return the root of new tree
18
/ \
20 13
先找到最右节点,从右往左依次更新节点值即可
3.代码:
int rr=0;
TreeNode* convertBST(TreeNode* root) {
if(root==NULL) return NULL;
else {
convertBST(root->right);
root->val+=rr;
rr=root->val;
convertBST(root->left);
}
return root;
}
4.感想:
这个题一开始想复杂了,总想着先去遍历一遍记录所有节点值,结果越走越远