Problem 538

Abstract / Summary

Transform 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 0538.py

class Solution:
    def convertBST(self, root: Optional[TreeNode]) -> Optional[TreeNode]:
        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
13 lines | 369 bytes | submitted September 1, 2023 | GitHub   tab size 4 | low complexity

Difficulty

This problem is ranked as
easy medium hard

and has an acceptance rate of about 72% (500k+ 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 defines a method that transforms a binary search tree (BST) into a greater-sum tree. In the resulting tree each node’s value becomes the sum of all original values that are greater than or equal to the node’s original value. The algorithm accomplishes this transformation in-place, returning the same root reference after mutation.

Key Steps

Initial accumulator

sum = 0

An integer variable named sum is created in the outer scope of the method. It serves as a running total of node values that have already been visited during the traversal. Because the traversal proceeds from the largest values downwards, this accumulator always holds the correct cumulative sum for the current node.

Recursive helper definition

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

A nested function deeper is declared to perform a depth-first walk of the tree. The function checks whether the current node is non-null before proceeding, which naturally skips absent children. The body of the function follows three logical phases:

  1. Traverse the right subtree - deeper(node.right) moves to the subtree containing larger values, ensuring those values are processed first.
  2. Update the accumulator and node - nonlocal sum grants the inner function access to the outer sum. The node’s original value is added to sum, and the node’s value is overwritten with the new total.
  3. Traverse the left subtree - deeper(node.left) processes the remaining smaller values after the current node has been updated.

Invocation and return

deeper(root)
return root

The helper is launched with the original root, causing the entire tree to be visited exactly once. After the traversal completes, the mutated root is returned to the caller.

Edge Cases Handled

When the input root is None, the outer method still creates the accumulator and defines the helper, but the first call deeper(root) immediately encounters a falsy node and returns without performing any work. Consequently the method returns None, correctly representing an empty tree.

A tree consisting of a single node follows the same path: the right-side recursion terminates instantly, the accumulator receives the sole value, the node is updated to that value, and the left-side recursion ends. The result is a tree where the single node’s value equals its original value, which matches the definition of a greater-sum tree for a one-element set.

Trees that are heavily skewed to the left (only left children) or to the right (only right children) are also accommodated. The recursion respects the absence of a child by checking if node: before each descent, so the algorithm never attempts to dereference a null pointer. The order of visitation-right, node, left-remains valid regardless of the shape, guaranteeing correct cumulative sums for every configuration.

Performance Optimizations

The algorithm achieves its goal without allocating auxiliary containers such as stacks or lists. By using a nonlocal variable, the running total is stored in a single scalar that is shared across all recursive frames, eliminating the need to pass the accumulator as a function argument. This reduces the overhead associated with argument handling and keeps the memory footprint minimal.

In-place mutation of each node’s val field avoids the creation of new node objects. Consequently the transformation reuses the existing tree structure, leading to lower allocation pressure and better cache locality because the same memory locations are updated sequentially during the traversal.

The recursion follows the natural depth of the BST, which is bounded by the tree’s height. No additional recursion depth is introduced beyond what is required to reach leaf nodes, preserving the stack usage at the theoretical minimum for a depth-first traversal. This design ensures that the algorithm scales efficiently with the size of the input tree while maintaining a straightforward control flow.

written by openai gpt

ELI5 - Simplified Explanation

Imagine a tall tree made of numbers where the biggest numbers are all on the right side and the smallest are on the left. This code walks through that tree to give every number a new, bigger value.

The code starts by visiting the very biggest number on the far right. It remembers that number and adds it to a secret pile. Then it moves to the next biggest number, takes the value from the secret pile, and updates the number to be the new sum of everything it has seen so far. It keeps doing this, traveling backward from the biggest numbers to the smallest ones. By the time it has visited every single part of the tree, every number has been changed into the total of itself plus all the numbers that were larger than it before. Think of it like a snowball rolling down a hill, picking up more snow and getting larger as it passes each spot.

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.73 | σ = 1.09

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++ Java Python TS
WalkCCC C++ Java Python
leetcode.ca C++ Java Python JS Go
LeetcodeHelp C++ Java Python
Progiez C++ Java Python
github BigEggStudy C#
black-shadows C++
charles-wangkai Java
everthis JS
fartem Ruby
fengvyi C++
fpdjsns C++
gouthampradhan Java
halfrost Go
haoel Python
JoshCrozier JS
keineahnung2345 C++
Krazune C++
linouk23 C++
lkwq007 Python
qiyuangong Java
ruoru Rust
sonugiri1043 C++
suxrobGM C#
trung-hn Python
varunu28 Java
vthwang Java
yuanliu666 Kotlin
YuriSpiridonov Python
zfang399 C++
AlgoMonster C++, Python, Java, TypeScript
WalkCCC C++, Python, Java
leetcode.ca C++, Go, Java, JavaScript, Python
LeetcodeHelp C++, Java, Python
Progiez C++, Java, Python
BigEggStudy C#
black-shadows C++, C++
charles-wangkai Java
everthis JavaScript
fartem Ruby
fengvyi C++
fpdjsns C++
gouthampradhan Java
halfrost Go
haoel Python
JoshCrozier JavaScript
keineahnung2345 C++
Krazune C++
linouk23 C++
lkwq007 Python
qiyuangong Java
ruoru Rust
sonugiri1043 C++
suxrobGM C#
trung-hn Python
varunu28 Java
vthwang Java
yuanliu666 Kotlin
YuriSpiridonov Python
zfang399 C++
43 links | 30 authors | 10 languages

Videos

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

Similar Problems

1 similar problem

Solved On The Same Day

30 solutions   September 1, 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