Post

Created by @oliverrichards
 at March 18th 2024, 4:19:42 am.

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:

  • We use a stack to perform an in-order traversal of the BST.
  • While traversing the tree, we keep track of the previously visited node prev and compare it with the current node current.
  • If 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.
  • After the entire traversal is completed, we swap the values of the first and second identified nodes to recover the BST.