The problem “Recover Binary Search Tree” involves correcting a binary search tree (BST) in which two of the nodes had their values swapped by mistake. The goal is to identify the two nodes that were swapped and recover the BST by swapping their values back to their correct positions.
Input:
Output:
For example:
Input: [1,3,null,null,2]
Tree structure:
1
/
3
\
2
Output: [3,1,null,null,2]
Tree structure corrected to:
3
/
1
\
2
```python class TreeNode: def init(self, val=0, left=None, right=None): self.val = val self.left = left self.right = right
class Solution: def recoverTree(self, root: TreeNode) -> None: # Variables to keep track of the two nodes to be swapped self.first = self.second = self.prev = None
def inorder(node: TreeNode):
if node is None:
return
# In-order traversal: left subtree
inorder(node.left)
# Identify the misplaced nodes
if self.prev and self.prev.val > node.val:
if not self.first:
self.first = self.prev
self.second = node
self.prev = node
# In-order traversal: right subtree
inorder(node.right)
# Perform the in-order traversal
inorder(root)
# Swap the values of the two nodes to correct the tree
if self.first and self.second:
self.first.val, self.second.val = self.second.val, self.first.val
Let’s implement the provided code to solve this problem efficiently.
Got blindsided by a question you didn’t expect?
Spend too much time studying?
Or simply don’t have the time to go over all 3000 questions?