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 13 Output: The root of a Greater Tree like this: 18 / \ 20 13
此题为中序遍历思想的应用,先root->right,再root,最后root->left;并把得到的和传入下一个结点。
class Solution { public: TreeNode* convertBST(TreeNode* root) { Inorder(root); return root; } int Inorder(TreeNode* root,int sum=0) { if(!root) return sum; else { sum=Inorder(root->right,sum); return sum=Inorder(root->left,root->val+=sum); } } };