Technical Interview Question: You are given a binary search tree (BST) with two elements swapped. Write a function to recover the BST such that its in-order traversal yields the correct order of nodes.
# Definition for a binary tree node
class TreeNode:
def __init__(self, val=0, left=None, right=None):
self.val = val
self.left = left
self.right = right
def recoverTree(root: TreeNode) -> None:
stack = []
# Step 1: Perform in-order traversal to identify the swapped nodes
first, second, prev = None, None, None
current = root
while stack or current:
while current:
stack.append(current)
current = current.left
current = stack.pop()
if prev and prev.val > current.val:
if not first:
first = prev
second = current
prev = current
current = current.right
# Step 2: Swap the values of the identified nodes
first.val, second.val = second.val, first.val
Explanation:
prev
and compare it with the current node current
.prev.val
is greater than current.val
, it indicates a pair of nodes that are incorrectly ordered. We store the first and second swapped nodes once we encounter them.