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
4mo
Convert a Binary Search Tree into a Greater Sum Tree by replacing each node's value with the sum of all nodes' values greater than the current node's value.
Traverse the BST in reverse inorder (right-r...read more
Help your peers!
Add answer anonymously...
MathWorks Software Developer Intern interview questions & answers
A Software Developer Intern was asked Q. Interest in Matlab
A Software Developer Intern was asked Q. Car Pooling Capacity Problem You are a cab driver with a car that initially has ...read more
A Software Developer Intern was asked Q. Distance To Nearest 1 in a Binary Matrix Problem Given a binary matrix MAT conta...read more
Popular interview questions of Software Developer Intern
A Software Developer Intern was asked Q1. Interest in Matlab
A Software Developer Intern was asked Q2. Car Pooling Capacity Problem You are a cab driver with a car that initially has ...read more
A Software Developer Intern was asked Q3. Distance To Nearest 1 in a Binary Matrix Problem Given a binary matrix MAT conta...read more
>
MathWorks Software Developer Intern Interview Questions
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

