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
Difficulty
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
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 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:
- Traverse the right subtree -
deeper(node.right)moves to the subtree containing larger values, ensuring those values are processed first. - Update the accumulator and node -
nonlocal sumgrants the inner function access to the outersum. The node’s original value is added tosum, and the node’s value is overwritten with the new total. - 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.
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.
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++ | 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++ |
Videos
Similar Problems
- problem 1038: Binary Search Tree to Greater Sum Tree
Solved On The Same Day
- problem 144: Binary Tree Preorder Traversal
- problem 145: Binary Tree Postorder Traversal
- problem 222: Count Complete Tree Nodes
- problem 404: Sum of Left Leaves
- problem 501: Find Mode in Binary Search Tree
- problem 543: Diameter of Binary Tree
- problem 559: Maximum Depth of N-ary Tree
- problem 589: N-ary Tree Preorder Traversal
- problem 590: N-ary Tree Postorder Traversal
- problem 637: Average of Levels in Binary Tree
- problem 700: Search in a Binary Search Tree
- problem 703: Kth Largest Element in a Stream
- problem 79: Word Search
- problem 81: Search in Rotated Sorted Array II
- problem 97: Interleaving String
- problem 99: Recover Binary Search Tree
- problem 173: Binary Search Tree Iterator
- problem 199: Binary Tree Right Side View
- problem 230: Kth Smallest Element in a BST
- problem 235: Lowest Common Ancestor of a Binary Search Tree
- problem 341: Flatten Nested List Iterator
- problem 429: N-ary Tree Level Order Traversal
- problem 508: Most Frequent Subtree Sum
- problem 513: Find Bottom Left Tree Value
- problem 65: Valid Number
- problem 85: Maximal Rectangle
- problem 87: Scramble String
- problem 126: Word Ladder II
- problem 127: Word Ladder
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