#538
Convert BST to Greater 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)
In the optimal approach, we perform a reverse in-order traversal of the BST. This way, we can keep a running total of the sum of all nodes we've visited so far, allowing us to update each node efficiently.
⚙️
Algorithm
3 steps- 1Step 1: Initialize a variable to keep track of the cumulative sum (let's call it 'total').
- 2Step 2: Perform a reverse in-order traversal (right -> node -> left) of the tree.
- 3Step 3: For each node visited, update its value by adding the current 'total' to it, then update 'total' with the new value of the node.
solution.py19 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
8def convertBST(root):
9 total = 0
10 def reverse_inorder(node):
11 nonlocal total
12 if not node:
13 return
14 reverse_inorder(node.right)
15 total += node.val
16 node.val = total
17 reverse_inorder(node.left)
18 reverse_inorder(root)
19 return rootℹ
Complexity note: The time complexity is O(n) because 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.
- 1The reverse in-order traversal allows us to efficiently calculate the cumulative sum of greater nodes.
- 2Understanding the properties of a BST is crucial for optimizing tree-related problems.
Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.