VOOZH about

URL: https://www.geeksforgeeks.org/dsa/transform-bst-sum-tree/

⇱ Transform a BST to greater sum tree - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Transform a BST to greater sum tree

Last Updated : 11 Oct, 2025

Given the root of Binary Search Tree, transform it into a greater sum tree where each node contains the sum of all nodes greater than that node.

Example:

Input:

πŸ‘ Transform-a-BST-to-greater-sum-tree

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.

πŸ‘ 420046793

[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.


Output
119 
137 75 
139 130 104 0 
N N N N N N 40 N 
Comment
Article Tags: