Problem Statement in English
You’re given the root of a binary search tree (BST), where exactly two nodes of the tree were swapped by mistake. Recover the tree without changing its structure.
You need to solve the problem without using any extra space (i.e., constant space).
Approach
Since it’s a binary search tree, we can do an in order traversal to get a sorted view of the tree. They’ve guaranteed that exactly two nodes are swapped, so we can find the two nodes that are out of order and swap them back.
For the constant space requirement, we can use Morris Traversal to do an in order traversal without using a stack or recursion.
There are basically 2 scenarios for the swapped nodes:
- The swapped nodes are adjacent in the in-order traversal. For example, in the sequence [1, 3, 2, 4], the nodes 3 and 2 are swapped.
- The swapped nodes are not adjacent in the in-order traversal. For example, in the sequence [1, 4, 3, 2, 5], the nodes 4 and 2 are swapped.
For both scenarios, we can identify the two nodes that are out of order during the in-order traversal and swap their values back to recover the BST.
We track the first node that is out of order (the first node that is greater than its next node) and the second node that is out of order (the second node that is less than its previous node). After the traversal, we swap the values of these two nodes to recover the BST.
And we’re done!
Solution in Python
class Solution:
def recoverTree(self, root: Optional[TreeNode]) -> None:
first = second = prev = None
curr = root
while curr:
if not curr.left:
# Check for BST violation
if prev and prev.val > curr.val:
if not first:
first = prev
second = curr
prev = curr
curr = curr.right
else:
# Find the in-order predecessor
pred = curr.left
while pred.right and pred.right != curr:
pred = pred.right
if not pred.right:
# Establish temporary thread
pred.right = curr
curr = curr.left
else:
# Break thread and process node
pred.right = None
if prev and prev.val > curr.val:
if not first:
first = prev
second = curr
prev = curr
curr = curr.right
# Swap the values of the two identified nodes to recover the BST
if first and second:
first.val, second.val = second.val, first.val
Complexity
Time: $O(n)$
Since we are doing a Morris Traversal, we visit each node at most twice, leading to a linear time complexity.Space: $O(1)$
Since we are using Morris Traversal, we are not using any extra space for recursion or a stack, leading to constant space complexity.
Mistakes I Made
I had to look this up :(
And we are done.