Skip to content
Problem 538 · LeetCode 538(opens in a new tab)

Convert BST to Greater Tree

MediumBinary search trees

A binary search tree with all-different values is passed in as its root node. Change the tree in place so that every node holds its original value plus the sum of all values in the tree that are larger than it.

Return the root of the changed tree. The shape of the tree stays the same; only the values change.

Example 1

Input:  root = [5, 2, 8, 1, 3, null, 9]
Output: [22, 27, 17, 28, 25, null, 9]
Why:    5 becomes 5 + 8 + 9 = 22; 9 has nothing larger
2 more examples and the constraints

Example 2

Input:  root = [-3, null, 4]
Output: [1, null, 4]
Why:    −3 + 4 = 1; 4 stays 4

Example 3

Input:  root = []
Output: []
Why:    an empty tree stays empty

Constraints

  • 0 ≤ number of nodes ≤ 10,000
  • −10,000 ≤ Node.val ≤ 10,000
  • All values are distinct
  • The input is a valid binary search tree

Your turn first

Have a go on paper or in your own editor, then reveal the approaches from the simplest up.

Try it on LeetCode(opens in a new tab)
  1. In-order list + suffix sumsO(n)
  2. Reverse in-order, running sumO(n)

The idea in one sentence

The pattern, how to spot it, and the best complexity.

Side by side

ApproachTimeRelative work for 10,000 nodesVerdict
In-order list + suffix sumsO(n)
Passes; O(n) extra memory
Reverse in-order, running sumO(n)
Best; one walk, no list

n = number of nodes, h = height of the tree.

Edge cases to test

  • Empty tree. Return null (an empty list) without touching anything.
  • Single node. Nothing is larger, so its value stays the same.
  • Negative values. Larger values can be negative and shrink the total: in [−3, −5] the root −3 stays −3 and −5 becomes −8.
  • A long chain. 10,000 nodes in a line: use an explicit stack so deep recursion cannot overflow.

Common mistakes

  • Walking left first, which adds the smaller values instead of the larger ones.
  • Writing the new value before adding it to the total, so the total picks up sums twice.
  • Building a new tree instead of updating the values in place, and losing the shape.

How to talk through it

  1. 1Clarify. Is the tree changed in place? Are values distinct? Can it be empty?
  2. 2Use the BST order. In-order is sorted, so "all larger values" is a suffix of that order.
  3. 3Give the list version. Collect in order, then suffix sums from the end: O(n) time and memory.
  4. 4Reverse the walk. Right, node, left reads largest first; a running total updates each node on the spot.
  5. 5Test out loud. Run an empty tree, one node, negative values and a long chain.
Was this problem useful?Your vote tells us what to improve next.
Found a bug in our code, or something unclear?