题目:
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.
样例
Given a binary search Tree `{5,2,3}`:
5
/ \
2 13
Return the root of new tree
18
/ \
20 13
代码:
class Solution { public: /** * @param root the root of binary tree * @return the new root */ // Write your code here int sum=0; void travel(TreeNode* root) { if(root==NULL) return ; if (root->right) { travel(root->right); } sum+=(root->val); root->val=sum; if (root->left) { travel(root->left); } } TreeNode* convertBST(TreeNode* root) { travel(root); return root; } };
思想:从右往左递归累计加值,然后复制给当前节点。