Binary Search Tree to Greater Sum Tree (LeetCode 1038): Solution and Explanation

Medium
Tree
Depth First Search
Binary Search Tree
Binary Tree

Given a binary search tree with distinct values, replace each node's value with itself plus the sum of all larger values in the tree, then return the root.

Intuition

Write the tree's values in sorted order. The new value of any node is the sum of its own value and everything to its right in that list, which is a suffix sum.

Suffix sums are easy if you read the list from the end: keep a running total, add each value as you meet it, and the total at that moment is the answer for that value.

An inorder traversal (left, node, right) reads a BST in increasing order. Flip it to right, node, left and it reads from the largest value down. So a reversed inorder walk with one running total rewrites every node in a single pass.

Approach: Reverse inorder traversal with an explicit stack

  1. Set total = 0 and start the cursor at the root.
  2. Walk right as far as possible, pushing each node on the stack. The top is now the largest value not yet visited.
  3. Pop a node, add its value to total, and write total back into the node.
  4. Move the cursor to the popped node's left child and repeat.
  5. When the stack is empty and the cursor is null, return the root.

Step-by-step example

root = [4,1,6,0,2,5,7,null,null,null,3,null,null,null,8]
  1. Push 4, 6, 7, 8 walking right. Pop 8: total = 8, the node stays 8.
  2. Pop 7: total = 15. Pop 6: total = 21. Its left child 5 is pushed and popped: total = 26.
  3. Pop 4: total = 30. Move to its left subtree: push 1 and 2 and 3 along the right side.
  4. Pop 3: total = 33. Pop 2: total = 35. Pop 1: total = 36. Pop 0: total = 36.
  5. Return the root, which now reads [30,36,21,36,35,26,15,null,null,null,33,null,null,null,8].

Code: Python, Java, C++

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

Time and space complexity

Time

O(n)

Each node is pushed and popped exactly once.

Space

O(h)

The stack holds at most one root-to-node path, so it is bounded by the tree height h.

Other approaches

Recursive reverse inorder (time O(n), space O(h))

Recurse into the right subtree, update the node with the running total, then recurse left. It is the same traversal with the call stack instead of an explicit one.

Collect, sum, rewrite (time O(n), space O(n))

Gather the values with an inorder walk, build suffix sums in an array, then do a second inorder walk to write them back. Simple, but it uses O(n) extra space and two passes.

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

A reverse Morris traversal threads temporary links to avoid any stack, getting O(1) extra space at the cost of more intricate code.

Common mistakes

  • Walking left first. A normal inorder walk visits small values first, so the running total would hold smaller values instead of larger ones.
  • Adding the new value of a node to the total instead of its original value. Update total with node.val before you overwrite it.
  • Resetting the total inside recursion. The running sum must be shared across the whole traversal, not passed down as a local copy.
  • Building a new tree. The problem asks for the same tree with updated values; returning the original root is enough.

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 on the left is smaller. Visiting right first, then the node, then left therefore lists values from largest to smallest.

Is this the same as LeetCode 538, Convert BST to Greater Tree?

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

Does the tree shape change?

No. Only the values change. The output keeps every node and link exactly where it was.