Add all greater values to every node in a given BST
Given a Binary Search Tree (BST), modify it so that all greater values in the given BST are added to every node. For example, consider the following BST.
50 / \ 30 70 / \ / \ 20 40 60 80 The above tree should be modified to following 260 / \ 330 150 / \ / \ 350 300 210 80
Become a success story instead of just reading about them. Prepare for coding interviews at Amazon and other top product-based companies with our Amazon Test Series. Includes topic-wise practice questions on all important DSA topics along with 10 practice contests of 2 hours each. Designed by industry experts that will surely help you practice and sharpen your programming skills. Wait no more, start your preparation today!
A simple method for solving this is to find the sum of all greater values for every node. This method would take O(n^2) time.
The method discussed in this article uses the technique of reverse in-order tree traversal of BST which optimizes the problem to be solved in a single traversal.
Approach: In this problem as we could notice that the largest node would remain the same. The value of 2nd largest node = value of largest + value of second largest node. Similarly, the value of nth largest node will be the sum of the n-th node and value of (n-1)th largest node after modification. So if we traverse the tree in descending order and simultaneously update the sum value at every step while adding the value to the root node, the problem would be solved.
So to traverse the BST in descending order we use reverse in-order traversal of BST. This takes a global variable sum which is updated at every node and once the root node is reached it is added to the value of root node and value of the root node is updated.
350 330 300 260 210 150 80
- Time Complexity: O(n).
As this problem uses an in-order tree traversal technique
- Auxiliary Space: O(1).
As no data structure has been used for storing values.
As a side note, we can also use reverse Inorder traversal to find the kth largest element in a BST.
This article is contributed by Chandra Prakash. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.