Problem 1038

Abstract / Summary

Convert a binary search tree so each node's value becomes the sum of its original value and all values greater than it

Note

The full problem description, including helpful examples, can be found on LeetCode.

Python 1038.py

class Solution:
    def bstToGst(self, root: TreeNode) -> TreeNode:
        # copied from problem 538
        sum = 0
        def deeper(node):
            if node:
                deeper(node.right)
                nonlocal sum
                sum += node.val
                node.val = sum
                deeper(node.left)

        deeper(root)
        return root
14 lines | 382 bytes | submitted November 23, 2023 | GitHub   8% comment ratio | tab size 4 | low complexity

Difficulty

This problem is ranked as
easy medium hard

and has an acceptance rate of about 88% (300k+ submissions).

Typical patterns to solve this problem:
  • Binary Search Tree
  • Binary Tree
  • Depth First Search
  • Tree
I solved 663 easy, 1250 medium and 309 hard problems

AI Disclaimer

Every single line of code was written by me, 100% from scratch, between August 2023 and August 2024.
However, two years later I set up this website and used various AI tools to generate most of the walkthrough / explanations below.

See this dedicated page for more details.
LeetCode profile | GitHub repo

Code Walkthrough

Overview

The provided implementation converts a binary search tree (BST) into a greater-sum tree (GST). In a GST each node’s value becomes the sum of all original node values that are greater than or equal to it. The solution follows a depth-first traversal that visits nodes in descending order, accumulating a running total and updating each node in place. The function returns the transformed tree root, preserving the original structure while mutating node values.

Core Algorithm

The transformation hinges on a reverse in-order traversal (right → node → left). This order guarantees that when a node is processed, all nodes with larger original values have already been visited and their contributions are reflected in the accumulated sum. The algorithm uses a closure variable sum to keep the running total across recursive calls.

sum = 0
def deeper(node):
    if node:
        deeper(node.right)
        nonlocal sum
        sum += node.val
        node.val = sum
        deeper(node.left)

The outer method initiates the recursion with the tree root and returns the mutated root:

deeper(root)
return root

The nonlocal declaration allows the inner function to modify the sum variable defined in the enclosing scope, ensuring that the cumulative total is shared across all recursive invocations.

Edge Cases

The recursion begins with a guard if node: which naturally handles a None root, returning None without further work. This also covers leaf nodes: when a leaf’s left and right children are None, the recursive calls terminate immediately, and the leaf’s value is updated based on the current sum. Because the traversal order processes the right subtree before the node itself, any subtree that is empty (e.g., a node with only a left child) still receives the correct accumulated sum from previously visited right-side nodes. The algorithm therefore correctly handles trees that are completely skewed to the left, completely skewed to the right, or contain a mixture of missing children.

Performance Characteristics

The solution performs a single pass over the tree, visiting each node exactly once. By updating node values during the traversal, it avoids the need for auxiliary data structures such as stacks or lists to store intermediate results. The use of recursion leverages the call stack to manage traversal state, which is efficient for balanced trees where the depth is logarithmic relative to the number of nodes. Even in the worst-case scenario of a highly unbalanced tree, the algorithm still processes each node in constant time per visit, resulting in a linear overall execution profile. The in-place mutation eliminates extra memory allocation for a new tree, keeping the additional space usage limited to the recursion stack.

written by openai gpt

ELI5 - Simplified Explanation

Imagine a tree made of numbers. In this tree, some numbers are bigger and some are smaller, and they are arranged in a special way where the ones on the right side are always the biggest. The goal of this code is to change every number in the tree so that it becomes the sum of itself and all the numbers that are even bigger than it.

To do this, the code starts by keeping a running total, which begins at zero. It uses a helper function that acts like a visitor walking through the tree. To make sure the visitor adds up all the bigger numbers first, it walks to the very far right side of the tree where the biggest numbers live. Once it visits a number, it adds that number to the running total. Then, it updates the current number to be equal to this new total. Because it visits the right side first and then moves toward the left, it always knows the correct sum of everything larger. It repeats this until it has visited every single part of the tree, carefully updating each piece along the way.

written by google gemini

Code Quality

Several LLMs ranked my code quality on a scale from 1 (very poor) to 10 (outstanding):
n = 26 | median = 8 | μ = 7.65 | σ = 0.96

Complexity Analysis

Time: linear
As a rule of thumb, the maximum input size for one second execution time is
  • factorial: up to 10 elements
  • exponential: up to 20 elements
  • polynomial: a few thousand elements
  • loglinear: up to 100,000 elements
  • linear: a few million elements
  • logarithmic: a billion elements
  • constant: practically unlimited
generated automatically

Other Solutions

I wrote a basic crawler to find other solutions to that problem.
Obviously, I did that after I solved the problem myself.

In general, AlgoMonster and WalkCCC solutions are high-quality and always worth a look.
I haven't checked most of the other solutions, but they might be helpful as well.

And of course, the LeetCode forum is always a good place (or even the best) to look for alternative approaches.

(click on a column header to sort the table)
author
author solutions
www AlgoMonster C++ Python Java TS
WalkCCC C++
leetcode.ca C++ Python JS Java Go C Rust TS
LeetcodeHelp C++ Python Java
MemoryLimitExceeded C++ Python
Progiez C++ Python Java
github BigEggStudy C#
black-shadows C++
charles-wangkai Java
DimitrisJim C
everthis JS
fartem Ruby
fsq C++
Garvit244 Python
halfrost Go
JoshCrozier JS
keineahnung2345 C++
Krazune C++
lkwq007 Python
shreymehul C#
suxrobGM C#
varunu28 Java
YuriSpiridonov Python
AlgoMonster C++, Python, Java, TypeScript
WalkCCC C++
leetcode.ca C, C++, Go, Java, JavaScript, Python, Rust, TypeScript
LeetcodeHelp C++, Java, Python
MemoryLimitExceeded Python, C++
Progiez C++, Java, Python
BigEggStudy C#
black-shadows C++, C++
charles-wangkai Java
DimitrisJim C
everthis JavaScript
fartem Ruby
fsq C++
Garvit244 Python
halfrost Go
JoshCrozier JavaScript
keineahnung2345 C++
Krazune C++
lkwq007 Python
shreymehul C#
suxrobGM C#
varunu28 Java
YuriSpiridonov Python
38 links | 23 authors | 10 languages

Videos

8 videos   did my crawler come up with invalid videos ? drop me a line.

Similar Problems

1 similar problem

Solved On The Same Day

15 solutions   November 23, 2023

Extra

There are a few extra pages giving you some insights into my setup:
  • Tech Stack - my development environment and tools
  • AI - how AI helped me create this website (NOT solving the problems)
  • Progress - progression over time
  • Quality - code quality