Output: [[119], [137, 75], [139, 130, 104, 0], [N, N, N, N, N, N, 40, N]] Explanation: Every Node contains the sum of nodes greater then current node's value.
[Naive Approach] By Calculating Sum for Each Node - O(n^2) Time and O(n) Space
The idea is to traverse the tree, and for each node, calculate the sum of all nodes greater than the current node and store this sum for that node. Then, traverse the tree again and replace each nodeβs value with its corresponding sum.
Output
134
152 90
154 145 119 50
N N N N N N N 0
[Expected Approach] Using Single Traversal - O(n) Time and O(n) Space
The idea is to optimize the above approach. Rather than calculating the sum for each node separately, we traverse the tree in reverse in-order (right β root β left) while keeping a running sum of all previously visited nodes. Each nodeβs value is updated to this running sum, ensuring it contains the sum of all nodes greater than itself.