Problem Description
Given the root of a Binary Search Tree (BST), convert it into a Greater Tree such that every key of the original BST is changed to the original key plus the sum of all keys greater than the original key in the BST.
Key Insights
- Utilize the properties of BST where the right subtree contains larger values.
- Traverse the tree in reverse in-order (right, node, left) to accumulate the sum of greater values.
- Maintain an accumulator to update each node's value as you traverse.
Space and Time Complexity
Time Complexity: O(n) - every node is visited once.
Space Complexity: O(h) - where h is the height of the tree; in the worst-case scenario (skewed tree), it can be O(n).
Solution
The solution employs a reverse in-order depth-first traversal:
- Start with the rightmost (largest) node.
- Use an accumulator variable to keep track of the total sum of visited nodes.
- For each node visited, add its value to the accumulator, then update the node's value with the accumulator.
- Continue to the left subtree.
- This traversal takes advantage of the BST structure, ensuring that at each node, the accumulator holds the sum of all nodes that have greater values.