Given a Binary Search Tree(BST), convert it to a Binary Tree such that every key of the original BST is changed to a key plus the sum of all smaller keys in BST.
Explanation: Every key of the original BST is changed to a key plus the sum of all smaller keys in BST.
Approach:
The idea is to use recursion to traverse the tree in inorder manner while keeping a running sum of all previously visited nodes. The value of each node is updated to this running sum, which ensure that each node contains the sum of all nodes less than or equal to it.
Below is the implementation of the above approach:
Output
1 3 10 21 36 65 105 155
Time Complexity: O(n), where n is the number of nodes in given Binary Tree, as it does a simple traversal of the tree. Auxiliary Space: O(h), where h is the height of tree.