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
Difficulty
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
AI Disclaimer
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.
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.
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.
Code Quality
Complexity Analysis
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
Other Solutions
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 |
Videos
Similar Problems
- problem 538: Convert BST to Greater Tree
Solved On The Same Day
- problem 2932: Maximum Strong Pair XOR I
- problem 731: My Calendar II
- problem 792: Number of Matching Subsequences
- problem 820: Short Encoding of Words
- problem 911: Online Election
- problem 950: Reveal Cards In Increasing Order
- problem 1023: Camelcase Matching
- problem 1170: Compare Strings by Frequency of the Smallest Character
- problem 1171: Remove Zero Sum Consecutive Nodes from Linked List
- problem 1696: Jump Game VI
- problem 2327: Number of People Aware of a Secret
- problem 432: All O`one Data Structure
- problem 732: My Calendar III
- problem 1044: Longest Duplicate Substring
Extra
- 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