KatInterview

99. Recover Binary Search Tree

MediumSolutions in Python, Java, C++, TypeScript

Read the full problem statement on LeetCode and try it first. Below is how to approach it in an interview, followed by a complete answer in each language.

Approach

Method: In-order Traversal with Constant Space (Morris Traversal)

Problem Analysis

Solution

Recover Binary Search Tree in Python

# 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
class Solution:
    def recoverTree(self, root: Optional[TreeNode]) -> None:
        """
        Do not return anything, modify root in-place instead.
        """
        first = None  # First node of the misplaced pair
        second = None # Second node of the misplaced pair
        prev = None   # Previous node in the in-order traversal
        current = root

        # Use Morris Traversal for O(1) space in-order traversal
        while current:
            if not current.left:
                # This is a visit in in-order sequence.
                # Check for a violation of BST property.
                if prev and prev.val > current.val:
                    if not first:
                        # This is the first violation found.
                        # The first element of the out-of-order pair is the previous node.
                        first = prev
                    # The second element is the current node.
                    # This will be updated if a second violation is found.
                    second = current
                
                prev = current
                current = current.right
            else:
                # Find the in-order predecessor of the current node.
                predecessor = current.left
                while predecessor.right and predecessor.right != current:
                    predecessor = predecessor.right
                
                if not predecessor.right:
                    # Create a temporary link (thread) from predecessor to current.
                    predecessor.right = current
                    # Move to the left subtree.
                    current = current.left
                else:
                    # The link already exists, so we are returning from the left subtree.
                    # Remove the thread.
                    predecessor.right = None
                    
                    # This is a visit in in-order sequence.
                    if prev and prev.val > current.val:
                        if not first:
                            first = prev
                        second = current
                    
                    prev = current
                    # Move to the right subtree.
                    current = current.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

Recover Binary Search Tree in Java

/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode() {}
 *     TreeNode(int val) { this.val = val; }
 *     TreeNode(int val, TreeNode left, TreeNode right) {
 *         this.val = val;
 *         this.left = left;
 *         this.right = right;
 *     }
 * }
 */
class Solution {
    public void recoverTree(TreeNode root) {
        TreeNode first = null;  // First node of the misplaced pair
        TreeNode second = null; // Second node of the misplaced pair
        TreeNode prev = null;   // Previous node in the in-order traversal
        TreeNode current = root;

        // Use Morris Traversal for O(1) space in-order traversal
        while (current != null) {
            if (current.left == null) {
                // This is a visit in in-order sequence.
                // Check for a violation of BST property.
                if (prev != null && prev.val > current.val) {
                    if (first == null) {
                        // This is the first violation found.
                        // The first element of the out-of-order pair is the previous node.
                        first = prev;
                    }
                    // The second element is the current node.
                    // This will be updated if a second violation is found.
                    second = current;
                }
                prev = current;
                current = current.right;
            } else {
                // Find the in-order predecessor of the current node.
                TreeNode predecessor = current.left;
                while (predecessor.right != null && predecessor.right != current) {
                    predecessor = predecessor.right;
                }

                if (predecessor.right == null) {
                    // Create a temporary link (thread) from predecessor to current.
                    predecessor.right = current;
                    // Move to the left subtree.
                    current = current.left;
                } else {
                    // The link already exists, so we are returning from the left subtree.
                    // Remove the thread.
                    predecessor.right = null;

                    // This is a visit in in-order sequence.
                    if (prev != null && prev.val > current.val) {
                        if (first == null) {
                            first = prev;
                        }
                        second = current;
                    }
                    prev = current;
                    // Move to the right subtree.
                    current = current.right;
                }
            }
        }

        // Swap the values of the two identified nodes to recover the BST.
        if (first != null && second != null) {
            int temp = first.val;
            first.val = second.val;
            second.val = temp;
        }
    }
}

Recover Binary Search Tree in C++

/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode() : val(0), left(nullptr), right(nullptr) {}
 *     TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
 *     TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
 * };
 */
class Solution {
public:
    void recoverTree(TreeNode* root) {
        TreeNode* first = nullptr; // First node of the misplaced pair
        TreeNode* second = nullptr; // Second node of the misplaced pair
        TreeNode* prev = nullptr; // Previous node in the in-order traversal
        TreeNode* current = root;

        // Use Morris Traversal for O(1) space in-order traversal
        while (current != nullptr) {
            if (current->left == nullptr) {
                // This is a visit in in-order sequence.
                // Check for a violation of BST property.
                if (prev != nullptr && prev->val > current->val) {
                    if (first == nullptr) {
                        // This is the first violation found.
                        // The first element of the out-of-order pair is the previous node.
                        first = prev;
                    }
                    // The second element is the current node.
                    // This will be updated if a second violation is found.
                    second = current;
                }
                prev = current;
                current = current->right;
            } else {
                // Find the in-order predecessor of the current node.
                TreeNode* predecessor = current->left;
                while (predecessor->right != nullptr && predecessor->right != current) {
                    predecessor = predecessor->right;
                }

                if (predecessor->right == nullptr) {
                    // Create a temporary link (thread) from predecessor to current.
                    predecessor->right = current;
                    // Move to the left subtree.
                    current = current->left;
                } else {
                    // The link already exists, so we are returning from the left subtree.
                    // Remove the thread.
                    predecessor->right = nullptr;
                    
                    // This is a visit in in-order sequence.
                    if (prev != nullptr && prev->val > current->val) {
                        if (first == nullptr) {
                            first = prev;
                        }
                        second = current;
                    }
                    prev = current;
                    // Move to the right subtree.
                    current = current->right;
                }
            }
        }

        // Swap the values of the two identified nodes to recover the BST.
        if (first != nullptr && second != nullptr) {
            std::swap(first->val, second->val);
        }
    }
};

Recover Binary Search Tree in TypeScript

/**
 * Definition for a binary tree node.
 * class TreeNode {
 *     val: number
 *     left: TreeNode | null
 *     right: TreeNode | null
 *     constructor(val?: number, left?: TreeNode | null, right?: TreeNode | null) {
 *         this.val = (val===undefined ? 0 : val)
 *         this.left = (left===undefined ? null : left)
 *         this.right = (right===undefined ? null : right)
 *     }
 * }
 */

/**
 Do not return anything, modify root in-place instead.
 */
function recoverTree(root: TreeNode | null): void {
    let first: TreeNode | null = null;    // First node of the misplaced pair
    let second: TreeNode | null = null;   // Second node of the misplaced pair
    let prev: TreeNode | null = null;     // Previous node in the in-order traversal
    let current: TreeNode | null = root;

    // Use Morris Traversal for O(1) space in-order traversal
    while (current !== null) {
        if (current.left === null) {
            // This is a visit in in-order sequence.
            // Check for a violation of BST property.
            if (prev !== null && prev.val > current.val) {
                if (first === null) {
                    // This is the first violation found.
                    // The first element of the out-of-order pair is the previous node.
                    first = prev;
                }
                // The second element is the current node.
                // This will be updated if a second violation is found.
                second = current;
            }
            prev = current;
            current = current.right;
        } else {
            // Find the in-order predecessor of the current node.
            let predecessor = current.left;
            while (predecessor.right !== null && predecessor.right !== current) {
                predecessor = predecessor.right;
            }

            if (predecessor.right === null) {
                // Create a temporary link (thread) from predecessor to current.
                predecessor.right = current;
                // Move to the left subtree.
                current = current.left;
            } else {
                // The link already exists, so we are returning from the left subtree.
                // Remove the thread.
                predecessor.right = null;
                
                // This is a visit in in-order sequence.
                if (prev !== null && prev.val > current.val) {
                    if (first === null) {
                        first = prev;
                    }
                    second = current;
                }
                prev = current;
                // Move to the right subtree.
                current = current.right;
            }
        }
    }

    // Swap the values of the two identified nodes to recover the BST.
    if (first !== null && second !== null) {
        const temp = first.val;
        first.val = second.val;
        second.val = temp;
    }
};

Preparing for interviews beyond LeetCode? Practise system design, SQL and behavioral questions with an in-browser runner on KatInterview.

LeetCode is a trademark of LeetCode LLC. KatInterview is not affiliated with LeetCode.