#1038
Binary Search Tree to Greater Sum Tree
MediumTreeDepth-First SearchBinary Search TreeBinary TreeDepth-First SearchTree Traversal
Approaches
Brute ForceOptimal
Complexity Comparison
| Brute Force | Optimal Solution★ | |
|---|---|---|
| Time | O(n²) | O(n) |
| Space | O(1) | O(h) |
💡
Intuition
Time O(n)Space O(h)
By using a reverse in-order traversal, we can efficiently calculate the cumulative sum of values as we traverse the tree. This allows us to update each node in a single pass.
⚙️
Algorithm
3 steps- 1Step 1: Initialize a variable to keep track of the cumulative sum.
- 2Step 2: Perform a reverse in-order traversal (right -> node -> left).
- 3Step 3: For each node, add its value to the cumulative sum and update the node's value.
solution.py18 lines
1# Full working Python code
2class TreeNode:
3 def __init__(self, val=0, left=None, right=None):
4 self.val = val
5 self.left = left
6 self.right = right
7
8class Solution:
9 def convertBST(self, root: TreeNode) -> TreeNode:
10 self.cumulative_sum = 0
11 def reverse_in_order(node):
12 if node:
13 reverse_in_order(node.right)
14 self.cumulative_sum += node.val
15 node.val = self.cumulative_sum
16 reverse_in_order(node.left)
17 reverse_in_order(root)
18 return rootℹ
Complexity note: The time complexity is O(n) since we visit each node exactly once. The space complexity is O(h) due to the recursion stack, where h is the height of the tree.
- 1Using reverse in-order traversal allows us to efficiently calculate the cumulative sum in a single pass.
- 2Understanding the properties of a BST is crucial for optimizing the traversal.
Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.