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
andDATA
!= -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!
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.
Stay ahead in your career. Get AmbitionBox app


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
AmbitionBox Awards
Get AmbitionBox app

