Explanation: The above tree represents the greater sum tree where each node contains the sum of all nodes greater than or equal to that node in original tree.
The root node 50 becomes 260 (sum of 50 + 60 + 70 + 80).
The left child of 50 becomes 330 (sum of 30 + 40 + 50 + 60 + 70 + 80).
The right child of 50 becomes 150 (70 + 80) and so on.
[Naive Approach] By Calculating Sum for Each Node - O(n^2) Time and O(n) Space
The idea is to traverse the binary tree and for each node, find the sum of all nodes with values greater than or equal to it. As we traverse, we compute these sums and replace the current node’s value with the corresponding sum.
This method doesn’t require the tree to be a BST. Following are the steps:
Traverse node by node (in-order, pre-order, etc.).
For each node, find all the nodes greater than equal to the current node and sum their values. Store all these sums.
Replace each node’s value with its corresponding sum by traversing in the same order as in Step 1.
Below is the implementation of the above approach:
Output
350 330 300 260 210 150 80
Note: Since this approach runs in O(n2) this will give TLE, so we need to think of a more efficient approach.
[Expected Approach] Using Single Traversal – O(n) Time and O(h) Space
The idea is to traverse the tree in reverse in-order (right -> root -> left) 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 greater than equal to it.
Below is the implementation of the above approach: