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 */ int ans=0; int dfs(TreeNode* root){ if(root==NULL)return 0; dfs(root->right); ans=root->val+ans; root->val=ans; dfs(root->left); } TreeNode* convertBST(TreeNode* root) { // Write your code here dfs(root); return root; } };