Convert BST to Greater Sum Tree

Given a Binary Search Tree (BST) of integers, your task is to convert it into a greater sum tree. In the greater sum tree, each node's value should be replaced with the sum of all nodes' values that are greater than the current node's value in the BST.

Example:

Input:
1
2 3
4 -1 5 6
-1 7 -1 -1 -1 -1
-1 -1
Output:
139 137 130 119 -1 104 75 -1 40 -1 -1 -1 -1 -1 -1

Explanation:

  • 11 is replaced by the sum of {15 + 29 + 35 + 40} = 119
  • 2 is replaced by the sum of {7 + 11 + 15 + 29 + 35 + 40} = 137
  • 29 is replaced by the sum of {35 + 40} = 75
  • 1 is replaced by the sum of {2 + 7 + 11 + 15 + 29 + 35 + 40} = 139
  • 7 is replaced by the sum of {11 + 15 + 29 + 35 + 40} = 130
  • 15 is replaced by the sum of {29 + 35 + 40} = 104
  • 40 is replaced by 0 (since there are no greater values than 40)
  • 35 is replaced by the sum of {40} = 40

Constraints:

  • 1 <= T <= 100
  • 0 <= N <= 1000
  • 0 <= DATA <= 10 ^ 4 and DATA != -1
Note:
You must modify the existing tree without creating a new tree. The input tree nodes are provided in level-order format, using -1 to indicate null nodes.
AnswerBot
1y

The task is to convert a Binary Search Tree into a Greater Sum Tree.

  • Traverse the BST in reverse inorder (right, root, left) to visit nodes in descending order.

  • Keep track of the sum of all greater node...read more

Help your peers!
Select
Add answer anonymously...

Deloitte Java Developer interview questions & answers

A Java Developer was asked 2mo agoQ. What is the difference between an abstract class and an interface?
A Java Developer was asked 2mo agoQ. How is a singleton class created?
A Java Developer was asked 2mo agoQ. Write code for the Singleton Pattern.

Popular interview questions of Java Developer

A Java Developer was asked 2mo agoQ1. What is the difference between an abstract class and an interface?
A Java Developer was asked 2mo agoQ2. How is a singleton class created?
A Java Developer was asked 2mo agoQ3. Write code for the Singleton Pattern.
Deloitte Java Developer Interview Questions
Stay ahead in your career. Get AmbitionBox app
play-icon
play-icon
qr-code
Trusted by over 1.5 Crore job seekers to find their right fit company
80 L+

Reviews

10L+

Interviews

4 Cr+

Salaries

1.5 Cr+

Users

Contribute to help millions

Made with ❤️ in India. Trademarks belong to their respective owners. All rights reserved © 2025 Info Edge (India) Ltd.

Follow Us
  • Youtube
  • Instagram
  • LinkedIn
  • Facebook
  • Twitter
Profile Image
Hello, Guest
AmbitionBox Employee Choice Awards 2025
Winners announced!
awards-icon
Contribute to help millions!
Write a review
Write a review
Share interview
Share interview
Contribute salary
Contribute salary
Add office photos
Add office photos
Add office benefits
Add office benefits