Problem Description
Given the root of a Binary Search Tree (BST), transform it into a Greater Tree such that every node's new value is equal to the sum of its original value plus the sum of all keys greater than the original node’s key in the BST.
Key Insights
- Use the BST property: nodes in the right subtree always have greater keys.
- Traverse the tree in reverse in-order (right, node, left) to process nodes in descending order.
- Maintain a running sum to accumulate values already visited.
- Update each node during the traversal by adding the running sum to its original value.
Space and Time Complexity
Time Complexity: O(n) (Each node is visited once.) Space Complexity: O(h) (h is the height of the tree, representing the recursion or stack height.)
Solution
The solution uses a reverse in-order traversal (visiting right subtree, node, then left subtree) because it processes nodes from the largest to the smallest. As you traverse the tree, you maintain a running sum of the values that have been visited so far. For each node, update its value by adding the running sum to its original value. This modified value properly represents the original value plus the sum of all greater keys in the BST.