#99
Recover Binary Search Tree
MediumTreeDepth-First SearchBinary Search TreeBinary TreeIn-order TraversalTree Traversal
Approaches
Brute ForceOptimal
Complexity Comparison
| Brute Force | Optimal Solution★ | |
|---|---|---|
| Time | O(n²) | O(n) |
| Space | O(1) | O(1) |
💡
Intuition
Time O(n)Space O(1)
The optimal solution uses an in-order traversal to identify the swapped nodes in a single pass while keeping track of the previous node. This approach is efficient and uses constant space.
⚙️
Algorithm
3 steps- 1Step 1: Initialize pointers for the previous node, first node, and second node.
- 2Step 2: Perform an in-order traversal of the tree, updating the previous node and checking for swapped nodes.
- 3Step 3: Swap the values of the identified nodes.
solution.py22 lines
1class TreeNode:
2 def __init__(self, val=0, left=None, right=None):
3 self.val = val
4 self.left = left
5 self.right = right
6
7class Solution:
8 def recoverTree(self, root: TreeNode) -> None:
9 self.first = self.second = self.prev = None
10 def inorder(node):
11 if not node:
12 return
13 inorder(node.left)
14 if self.prev and self.prev.val > node.val:
15 if not self.first:
16 self.first = self.prev
17 self.second = node
18 self.prev = node
19 inorder(node.right)
20
21 inorder(root)
22 self.first.val, self.second.val = self.second.val, self.first.valℹ
Complexity note: The time complexity is O(n) because we traverse each node exactly once. The space complexity is O(1) since we only use a few pointers, independent of the input size.
- 1In-order traversal of a BST gives sorted values.
- 2Only two nodes are swapped, so we only need to find those two nodes.
Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.