DSA Factory
Free Binary search trees lessonsBinary search trees · Stage 1 · Ordered walks · Step 4

Add everything that is bigger

Replace each value in a search tree by itself plus the sum of all values greater than it, by walking the tree from the largest value down while keeping a running total. About 14 minutes.

Largest first

Each node should end up holding its own value plus the sum of every value bigger than it. If you visit the nodes from the largest to the smallest, then when you arrive at a node, all the bigger values have already been seen.

The inorder walk goes smallest to largest. Swap the two recursive calls: right subtree first, then the node, then the left subtree.

Reverse inorder: right, node, left.
Running total: sum of everything seen so far.
In code
walk(node.right)
...
walk(node.left)
Greater tree for 4, 1, 6, 0, 2, 5, 7.
0124567
total
7

The largest is 7. Total 7, so 7 stays 7.

Move 1 of 4

Update in the middle

When the walk reaches a node, add the node's old value to the running total. The total now holds the node's value plus all larger values, which is exactly the new value. Store it in the node.

Do these two steps in this order, because the total must include the node's old value. After the whole walk, return the root: its shape did not change.

Add old value to the total, then store the total in the node.
Keep the shape: only the values change.
In code
total[0] += node.val
node.val = total[0]
Quick check

Why must the right subtree be visited before the node?

  1. AIts values are all bigger, and must be added to the total first
  2. BIts values are smaller
  3. CIt is simply the usual order
Show the answer

Its values are all bigger, and must be added to the total first. In a search tree the right side holds the larger values.

Your problem

Convert a search tree to a greater tree

Given the root of a binary search tree with different values, change every node's value so that it equals its original value plus the sum of all original values greater than it in the tree. Return the root.

Example
root = [4, 1, 6, 0, 2, 5, 7, null, null, null, 3, null, null, null, 8] → [30, 36, 21, 36, 35, 26, 15, null, null, null, 33, null, null, null, 8]

0 ≤ number of nodes ≤ 10,000 · 0 ≤ node.val ≤ 10,000 · it is a valid search tree

Solve it in your browserFree account, no card. Python, C++, Java or JavaScript, with hints if you get stuck, and your progress is saved.
Sign up free to solve