Convert BST to Greater Tree (Easy Amazon)
Input: The root of a Binary Search Tree like this:
5
/ \
2 13
Output: The root of a Greater Tree like this:
18
/ \
20 13Basic Idea:
class Solution { int sum = 0; public: // reverse in-order traversal TreeNode* convertBST(TreeNode* root) { if (root == nullptr) return root; convertBST(root->right); root->val = root->val + sum; sum = root->val; // 现在root->val就是包括之前root->val在内的大于它的node的val和了 convertBST(root->left); return root; } };