Binary Search Tree to Greater Sum Tree

Given the root of a binary search tree with distinct values, change every node so that its new value is the original value plus the sum of all values in the tree greater than it. Return the root of the modified tree.

30:00

Binary Search Tree to Greater Sum Tree
medium
Free written solution
Topics
Companies

Given the root of a binary search tree with distinct values, change every node so that its new value is the original value plus the sum of all values in the tree greater than it. Return the root of the modified tree.

Example 1:
Input: {"root":[4,1,6,0,2,5,7,null,null,null,3,null,null,null,8]}
Output: [30,36,21,36,35,26,15,null,null,null,33,null,null,null,8]
Constraints:
  • The number of nodes in the tree is in the range [1,100][1, 100].

  • 0≤Node.val≤1000 \leq \text{Node.val} \leq 100

  • All the values in the tree are unique.

Test Cases
Input (Stdin)
Expected Output (Stdout)
Execution Result

Run code to see results.

Input
arr ={"root":[4,1,6,0,2,5,7,null,null,null,3,null,null,null,8]}

Columns are in sorted order. Visit nodes from the largest value down (right, node, left), keeping a running total of everything seen.

416025738sorted012345678

stack (top first)

empty

total = 0

sum of every value visited so far, all at least as large as the next one

popped and rewritten
on stack
already rewritten
Variables
VariableValue
total0
node4
stack[]
DepthFunction Call
Stack empty
0/19