Convert BST to Greater Tree (LeetCode 538): Solution and Explanation

Medium
Tree
Depth First search
Binary search tree
Binary tree

Given a binary search tree with distinct values, replace each value with itself plus the sum of every larger value in the tree, and return the same tree. The shape stays exactly the same.

Intuition

Picture the values written out in sorted order. The new value for each key is that key plus everything to its right, which is a suffix sum.

Suffix sums are easy if you walk from the right end to the left end, keeping one running total.

An inorder traversal (left, node, right) reads a BST in ascending order. Flip it to right, node, left and you read it in descending order, which is exactly the right-to-left walk you want, without ever building the sorted list.

Approach: Reverse inorder traversal with a running total

  1. Set total = 0.
  2. Visit the right subtree first, so every larger value is added to total before the current node.
  3. Add the node's value to total, then overwrite the node's value with total.
  4. Visit the left subtree, whose values are all smaller and still need this total.
  5. Return the original root.

Step-by-step example

root = [4,1,6,0,2,5,7,null,null,null,3,null,null,null,8]
  1. From 4 go right to 6, right to 7, right to 8. Node 8 has no right child: total = 8, and 8 stays 8.
  2. Back at 7: total = 15, so 7 becomes 15. Back at 6: total = 21. Then 6's left child 5: total = 26.
  3. Back at the root 4: total = 30. Then the left side: 2's right child 3 gives 33, 2 gives 35, 1 gives 36.
  4. Finally 0 (left child of 1): total stays 36, so 0 becomes 36.
  5. Return the tree [30,36,21,36,35,26,15,null,null,null,33,null,null,null,8].

Code: Python, Java, C++

1class Solution:
2    def convertBST(self, root: Optional[TreeNode]) -> Optional[TreeNode]:
3        self.total = 0
4
5        def visit(node):
6            if not node:
7                return
8            visit(node.right)
9            self.total += node.val
10            node.val = self.total
11            visit(node.left)
12
13        visit(root)
14        return root
Press play on the visualizer and the running line lights up here.

Time and space complexity

Time

O(n)

Every node is visited once and does constant work.

Space

O(h)

The recursion stack is as deep as the tree height h: O(log n) for a balanced tree, O(n) for a chain.

Other approaches

Collect, then suffix-sum (time O(n), space O(n))

Gather the nodes with an inorder walk into a list, then loop over the list from the end, accumulating a sum and writing it back. Easy to reason about but stores all n nodes.

Iterative reverse inorder with a stack (time O(n), space O(h))

The same walk without recursion: push right children, pop, update, then move to the left child. Avoids deep recursion on chain-shaped trees.

Reverse Morris traversal (time O(n), space O(1))

Temporarily thread each node's inorder predecessor in the mirrored tree so the walk needs no stack, then remove the threads.

Common mistakes

  • Visiting left before right. That produces prefix sums of smaller values, the opposite of what is asked.
  • Writing the total into the node before adding the node's own value. Each new value must include the original key itself.
  • Keeping total as a field and not resetting it, so a second call starts with the previous call's sum.
  • Building a new tree. The problem expects the same nodes with new values; the shape must not change.

Frequently asked questions

Why does right, node, left give descending order?

In a BST everything in the right subtree is larger than the node and everything in the left subtree is smaller. Visiting right first, then the node, then left therefore lists values from largest to smallest at every level.

Is this the same as LeetCode 1038, Binary Search Tree to Greater Sum Tree?

Yes. Both ask for the same transformation and the same reverse inorder solution solves both.

Can the sum overflow?

Not within the limits: at most 10^4 nodes with absolute value at most 10^4 gives sums within 10^8, well inside a 32-bit integer.

What about negative values?

Nothing changes. The new value is still the key plus all larger keys, so a negative key can grow or shrink depending on what is above it.