Given a binary search tree, modify it such that every node is updated to contain the sum of all greater keys present in the BST.

For example, BST shown on the left should be updated to BST on the right.

 
Update Key in the BST

Practice this problem

1. Using Inorder Traversal

We can solve this problem by inorder traversal by calculating the sum of all nodes present in a binary tree in advance. Then for each node, the sum of all greater keys for any node can be updated in constant time using the total sum and sum of nodes visited so far.

Following is the C++, Java, and Python implementation of the idea:

C++


Download  Run Code

Output:

38 36 33 29 24 18 10

Java


Download  Run Code

Output:

38 36 33 29 24 18 10

Python


Download  Run Code

Output:

38 36 33 29 24 18 10

2. Using Reverse Inorder Traversal

The above solution traverses the tree two times. We can solve this problem in a single traversal by traversing the tree in reverse inorder. Now, keys will be visited in descending order, and the sum of all greater keys for any node can be updated in constant time by keeping track of the sum of nodes seen so far.

Following is the C++, Java, and Python program that demonstrates it:

C++


Download  Run Code

Output:

38 36 33 29 24 18 10

Java


Download  Run Code

Output:

38 36 33 29 24 18 10

Python


Download  Run Code

Output:

38 36 33 29 24 18 10

The time complexity of the above solution is O(n), where n is the size of the BST, and requires space proportional to the tree’s height for the call stack.