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...
Top Deloitte Java Developer interview questions & answers
Popular interview questions of Java Developer
Top HR questions asked in Deloitte Java Developer
Stay ahead in your career. Get AmbitionBox app
Helping over 1 Crore job seekers every month in choosing their right fit company
65 L+
Reviews
4 L+
Interviews
4 Cr+
Salaries
1 Cr+
Users/Month
Contribute to help millions
Get AmbitionBox app