The Wayback Machine - https://web.archive.org/web/20240624074908/https://www.geeksforgeeks.org/transform-bst-sum-tree/
Open In App

Transform a BST to greater sum tree

Last Updated : 06 Jan, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

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

sumBST

We strongly recommend minimizing the browser and try this yourself first.

Method 1 (Naïve): 

This method doesn’t require the tree to be a BST. Following are the steps. 

  1. Traverse node by node(Inorder, preorder, etc.) 
  2. For each node find all the nodes greater than that of the current node, sum the values. Store all these sums. 
  3. Replace each node value with their corresponding sum by traversing in the same order as in Step 1.

This takes O(n2) Time Complexity.

Method 2 (Using only one traversal):

By leveraging the fact that the tree is a BST, we can find an O(n) solution. The idea is to traverse BST in reverse inorder. Reverse inorder traversal of a BST gives us keys in decreasing order. Before visiting a node, we visit all greater nodes of that node. While traversing we keep track of the sum of keys which is the sum of all the keys greater than the key of the current node. 

Implementation:

C++




// C++ program to transform a BST to sum tree
#include<iostream>
using namespace std;
 
// A BST node
struct Node
{
    int data;
    struct Node *left, *right;
};
 
// A utility function to create a new Binary Tree Node
struct Node *newNode(int item)
{
    struct Node *temp =  new Node;
    temp->data = item;
    temp->left = temp->right = NULL;
    return temp;
}
 
// Recursive function to transform a BST to sum tree.
// This function traverses the tree in reverse inorder so
// that we have visited all greater key nodes of the currently
// visited node
void transformTreeUtil(struct Node *root, int *sum)
{
   // Base case
   if (root == NULL)  return;
 
   // Recur for right subtree
   transformTreeUtil(root->right, sum);
 
   // Update sum
   *sum = *sum + root->data;
 
   // Store old sum in current node
   root->data = *sum - root->data;
 
   // Recur for left subtree
   transformTreeUtil(root->left, sum);
}
 
// A wrapper over transformTreeUtil()
void transformTree(struct Node *root)
{
    int sum = 0; // Initialize sum
    transformTreeUtil(root, ∑);
}
 
// A utility function to print indorder traversal of a
// binary tree
void printInorder(struct Node *root)
{
    if (root == NULL) return;
 
    printInorder(root->left);
    cout << root->data << " ";
    printInorder(root->right);
}
 
// Driver Program to test above functions
int main()
{
    struct Node *root = newNode(11);
    root->left = newNode(2);
    root->right = newNode(29);
    root->left->left = newNode(1);
    root->left->right = newNode(7);
    root->right->left = newNode(15);
    root->right->right = newNode(40);
    root->right->right->left = newNode(35);
 
    cout << "Inorder Traversal of given tree\n";
    printInorder(root);
 
    transformTree(root);
 
    cout << "\n\nInorder Traversal of transformed tree\n";
    printInorder(root);
 
    return 0;
}


Java




// Java program to transform a BST to sum tree
import java.io.*;
class Node
{
  int data;
  Node left, right;
 
  // A utility function to create a new Binary Tree Node
  Node(int item)
  {
    data = item;
    left = right = null;
  }
}
 
class GFG
{
 
  static int sum = 0;
  static Node Root;
 
  // Recursive function to transform a BST to sum tree.
  // This function traverses the tree in reverse inorder so
  // that we have visited all greater key nodes of the currently
  // visited node
  static void transformTreeUtil(Node root)
  {
 
    // Base case
    if (root == null) 
      return;
 
    // Recur for right subtree
    transformTreeUtil(root.right);
 
    // Update sum
    sum = sum + root.data;
 
    // Store old sum in current node
    root.data = sum - root.data;
 
    // Recur for left subtree
    transformTreeUtil(root.left);
  }
 
  // A wrapper over transformTreeUtil()
  static void transformTree(Node root)
  {
 
    transformTreeUtil(root);
  }
 
  // A utility function to print indorder traversal of a
  // binary tree
  static void printInorder(Node root)
  {
    if (root == null)
      return;
    printInorder(root.left);
    System.out.print(root.data + " ");
    printInorder(root.right);
  }
 
  // Driver Program to test above functions
  public static void main (String[] args) {
 
    GFG.Root = new Node(11);
    GFG.Root.left = new Node(2);
    GFG.Root.right = new Node(29);
    GFG.Root.left.left = new Node(1);
    GFG.Root.left.right = new Node(7);
    GFG.Root.right.left = new Node(15);
    GFG.Root.right.right = new Node(40);
    GFG.Root.right.right.left = new Node(35);
 
    System.out.println("Inorder Traversal of given tree");
    printInorder(Root);
 
    transformTree(Root);
    System.out.println("\n\nInorder Traversal of transformed tree");
    printInorder(Root);
  }
}
 
// This code is contributed by avanitrachhadiya2155


Python3




# Python3 program to transform a BST to sum tree
 
class Node:
    def __init__(self, x):
        self.data = x
        self.left = None
        self.right = None
 
# Recursive function to transform a BST to sum tree.
# This function traverses the tree in reverse inorder so
# that we have visited all greater key nodes of the currently
# visited node
def transformTreeUtil(root):
   
   # Base case
   if (root == None):
        return
 
   # Recur for right subtree
   transformTreeUtil(root.right)
 
   # Update sum
   global sum
   sum = sum + root.data
 
   # Store old sum in current node
   root.data = sum - root.data
 
   # Recur for left subtree
   transformTreeUtil(root.left)
 
# A wrapper over transformTreeUtil()
def transformTree(root):
 
    # sum = 0 #Initialize sum
    transformTreeUtil(root)
 
# A utility function to prindorder traversal of a
# binary tree
def printInorder(root):
    if (root == None):
        return
 
    printInorder(root.left)
    print(root.data, end = " ")
    printInorder(root.right)
 
# Driver Program to test above functions
if __name__ == '__main__':
 
    sum=0
    root = Node(11)
    root.left = Node(2)
    root.right = Node(29)
    root.left.left = Node(1)
    root.left.right = Node(7)
    root.right.left = Node(15)
    root.right.right = Node(40)
    root.right.right.left = Node(35)
 
    print("Inorder Traversal of given tree")
    printInorder(root)
 
    transformTree(root)
 
    print("\nInorder Traversal of transformed tree")
    printInorder(root)
 
    # This code is contributed by mohit kumar 29


C#




// C# program to transform a BST to sum tree
using System;
 
public class Node
{
  public int data;
  public Node left, right;
 
  // A utility function to create a new Binary Tree Node
  public Node(int item)
  {
    data = item;
    left = right = null;
  }
}
 
public class GFG{
 
  static int sum = 0;
  static Node Root;
 
  // Recursive function to transform a BST to sum tree.
  // This function traverses the tree in reverse inorder so
  // that we have visited all greater key nodes of the currently
  // visited node
  static void transformTreeUtil(Node root)
  {
 
    // Base case
    if (root == null)
      return;
 
    // Recur for right subtree
    transformTreeUtil(root.right);
 
    // Update sum
    sum = sum + root.data;
 
    // Store old sum in current node
    root.data = sum - root.data;
 
    // Recur for left subtree
    transformTreeUtil(root.left);
  }
 
  // A wrapper over transformTreeUtil()
  static void transformTree(Node root)
  {
 
    transformTreeUtil(root);
  }
 
  // A utility function to print indorder traversal of a
  // binary tree
  static void printInorder(Node root)
  {
    if (root == null)
      return;
    printInorder(root.left);
    Console.Write(root.data + " ");
    printInorder(root.right);
  }
 
  // Driver Program to test above functions
 
  static public void Main (){
    GFG.Root = new Node(11);
    GFG.Root.left = new Node(2);
    GFG.Root.right = new Node(29);
    GFG.Root.left.left = new Node(1);
    GFG.Root.left.right = new Node(7);
    GFG.Root.right.left = new Node(15);
    GFG.Root.right.right = new Node(40);
    GFG.Root.right.right.left = new Node(35);
 
    Console.WriteLine("Inorder Traversal of given tree");
    printInorder(Root);
 
    transformTree(Root);
    Console.WriteLine("\n\nInorder Traversal of transformed tree");
    printInorder(Root);
  }
}
 
// This code is contributed by ab2127


Javascript




<script>
 
// Javascript program to transform
// a BST to sum tree
     
// A utility function to create a
// new Binary Tree Node
class Node
{
    constructor(item)
    {
        this.data = item;
        this.left=null;
        this.right=null;
    }
}
 
let sum = 0;
let Root;
 
// Recursive function to transform a BST
// to sum tree. This function traverses
// the tree in reverse inorder so that
// we have visited all greater key nodes
// of the currently visited node
function transformTreeUtil(root)
{
     
    // Base case
    if (root == null)
      return;
     
    // Recur for right subtree
    transformTreeUtil(root.right);
     
    // Update sum
    sum = sum + root.data;
     
    // Store old sum in current node
    root.data = sum - root.data;
     
    // Recur for left subtree
    transformTreeUtil(root.left);
}
 
// A wrapper over transformTreeUtil()
function transformTree(root)
{
    transformTreeUtil(root);
}
 
// A utility function to print indorder
// traversal of a binary tree
function printInorder(root)
{
    if (root == null)
          return;
           
    printInorder(root.left);
     
    document.write(root.data + " ");
    printInorder(root.right);
}
 
// Driver code
Root = new Node(11);
Root.left = new Node(2);
Root.right = new Node(29);
Root.left.left = new Node(1);
Root.left.right = new Node(7);
Root.right.left = new Node(15);
Root.right.right = new Node(40);
Root.right.right.left = new Node(35);
 
document.write("Inorder Traversal of given tree<br>");
printInorder(Root);
 
transformTree(Root);
document.write("<br><br>Inorder Traversal of " +
               "transformed tree<br>");
printInorder(Root);
 
// This code is contributed by unknown2108
     
</script>


Output

Inorder Traversal of given tree
1 2 7 11 15 29 35 40 

Inorder Traversal of transformed tree
139 137 130 119 104 75 40 0 

Time Complexity: O(n)  where n is the number of nodes in given Binary Tree, as it does a simple traversal of the tree.
Auxiliary Space: O(h) where h is the height of given Binary Tree due to Recursion



Previous Article
Next Article

Similar Reads

Maximum sub-tree sum in a Binary Tree such that the sub-tree is also a BST
Given a binary tree, the task is to print the maximum sum of nodes of a sub-tree which is also a Binary Search Tree.Examples: Input : 7 / \ 12 2 / \ \ 11 13 5 / / \ 2 1 38 Output:44 BST rooted under node 5 has the maximum sum 5 / \ 1 38 Input: 5 / \ 9 2 / \ 6 3 / \ 8 7 Output: 8 Here each leaf node represents a binary search tree also a BST with su
12 min read
Convert a BST to a Binary Tree such that sum of all greater keys is added to every key
Given a Binary Search Tree (BST), convert it to a Binary Tree such that every key of the original BST is changed to key plus sum of all greater keys in BST. Examples: Input: Root of following BST 5 / \ 2 13 Output: The given BST is converted to following Binary Tree 18 / \ 20 13 Method 1: Solution: Do reverse In order traversal. Keep track of the s
15+ min read
Two nodes of a BST are swapped, correct the BST
Two of the nodes of a Binary Search Tree (BST) are swapped. Fix (or correct) the BST. Input: x = 20, y = 8 10 / \ 5 8 / \ 2 20Output: 10 / \ 5 20 / \ 2 8 Input: x = 10 y = 5 10 / \ 5 8 / \ 2 20Output: 5 / \ 10 20 / \ 2 8 Recommended ProblemFixing Two swapped nodes of a BSTSolve Problem Approach: The in-order traversal of a BST produces a sorted arr
15+ min read
POTD Solutions | 15 Oct' 23 | Normal BST to Balanced BST
View all POTD Solutions Welcome to the daily solutions of our PROBLEM OF THE DAY (POTD). We will discuss the entire problem step-by-step and work towards developing an optimized solution. This will not only help you brush up on your concepts of Binary Search Trees but will also help you build up problem-solving skills. POTD 15 October: Normal BST t
5 min read
K'th Largest Element in BST when modification to BST is not allowed
Given a Binary Search Tree (BST) and a positive integer k, find the k'th largest element in the Binary Search Tree. For example, in the following BST, if k = 3, then output should be 14, and if k = 5, then output should be 10. We have discussed two methods in this post. The method 1 requires O(n) time. The method 2 takes O(h) time where h is height
15+ min read
Find k-th smallest element in BST (Order Statistics in BST)
Given the root of a binary search tree and K as input, find Kth smallest element in BST. For example, in the following BST, if k = 3, then the output should be 10, and if k = 5, then the output should be 14. Recommended: Please solve it on "PRACTICE" first, before moving on to the solution.Method 1: Using Inorder Traversal (O(n) time and O(h) auxil
15+ min read
Count pairs in BST with sum greater than K
Given a binary search tree containing N distinct nodes and a value K. The task is to count pairs in the given binary search tree whose sum is greater than the given value K. Examples: Input: 5 / \ 3 7 / \ / \ 2 4 6 8 k = 11Output: 6Explanation:There are 6 pairs which are (4, 8), (5, 7), (5, 8), (6, 7), (6, 8) and (7, 8).Input: 8 / \ 3 9 \ / \ 5 6 1
15+ min read
Smallest number in BST which is greater than or equal to N
Given a Binary Search Tree and a number N, the task is to find the smallest number in the binary search tree that is greater than or equal to N. Print the value of the element if it exists otherwise print -1. Examples: Input: N = 20 Output: 21 Explanation: 21 is the smallest element greater than 20. Input: N = 18 Output: 19 Explanation: 19 is the s
9 min read
Smallest number in BST which is greater than or equal to N ( Iterative Approach)
Given a Binary Search Tree and a number N, the task is to find the smallest number in the binary search tree that is greater than or equal to N. Examples: Input: N = 5 8 / \ 7 10 / / \ 2 9 13 Output: 7 As 7 is the smallest number in BST which is greater than N = 5. Input: N = 10 8 / \ 5 11 / \ 2 7 \ 3 Output: 11 As 11 is the smallest number in BST
8 min read
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 80Recommended PracticeAdd all greater values to every node in a BSTTry It!A simp
15+ min read
Article Tags :
Practice Tags :
three90RightbarBannerImg