Convert a Binary Search Tree (BST) to a Greater Sum Tree

Given a Binary Search Tree of integers, transform it into a Greater Sum Tree where each node's value is replaced with the sum of all node values greater than the current node's value in the BST.

Input:

The first line contains an integer 'T', representing the number of test cases. For each test case, the first line contains the BST elements in level order, separated by a space. Use -1 to denote null nodes. For example, the input for a tree can be written as:
1 2 3 4 -1 5 6 -1 7 -1 -1 -1 -1 -1 -1

Output:

For each test case, print the level order traversal of the Greater Sum Tree with nodes values printed in a single-space separated manner. Each test case result should be on a new line.

Example:

Input:
1
11 2 29 1 7 15 40 -1 -1 -1 -1 -1 -1 35 -1
Output:
119 137 75 139 130 104 0
Explanation:
For the input BST, the transformation results in each node being replaced by the sum of values greater than itself.

Constraints:

  • 1 <= 'T' <= 100
  • 0 <= 'N' <= 1000
  • 0 <= 'DATA' <= 104 and 'DATA' != -1

Note: You must modify the given tree directly without creating a new one.

AnswerBot
4mo

Convert a Binary Search Tree to a Greater Sum Tree by replacing each node's value with the sum of all node values greater than the current node's value.

  • Traverse the BST in reverse inorder (right, root...read more

Help your peers!
Select
Add answer anonymously...

Top Software Developer Interview Questions Asked at One Convergence

Q. Can you explain the memory layout of a C program?
Q. What is the difference between Zombie, Orphan, and Daemon processes?
Q. What is a symbol table?
Software 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