LeetCode 99: Recover Binary Search Tree Solution

Master LeetCode problem 99 (Recover Binary Search Tree), a medium challenge, with our optimized solutions in Java, C++, and Python. Explore detailed explanations, test your code in our interactive editor, and prepare for coding interviews.

99. Recover Binary Search Tree

Problem Explanation

Explanation

To recover the binary search tree, we need to identify the two nodes that are swapped incorrectly and then swap them back to restore the BST property. We can achieve this by performing an in-order traversal of the BST and keeping track of the previous node visited.

  1. Initialize three pointers first, middle, and last to null. Also, initialize a prev pointer to null.
  2. Perform an in-order traversal of the BST.
  3. During traversal, if the value of the current node is less than the value of the previous node, we have found a potential swap:
    • If first is null, set first to prev and middle to the current node.
    • If first is not null, set last to the current node.
  4. After traversal, swap the values of first and last nodes to correct the BST.

Time Complexity: O(n) - where n is the number of nodes in the BST
Space Complexity: O(1) - no extra space is used

Solution Code

class Solution {
    TreeNode first = null;
    TreeNode middle = null;
    TreeNode last = null;
    TreeNode prev = null;
    
    public void recoverTree(TreeNode root) {
        inorder(root);
        if (first != null && last != null) {
            int temp = first.val;
            first.val = last.val;
            last.val = temp;
        }
    }
    
    private void inorder(TreeNode node) {
        if (node == null) return;
        
        inorder(node.left);
        
        if (prev != null && node.val < prev.val) {
            if (first == null) {
                first = prev;
                middle = node;
            } else {
                last = node;
            }
        }
        
        prev = node;
        
        inorder(node.right);
    }
}

Try It Yourself

Loading code editor...

Related LeetCode Problems

Frequently Asked Questions

How to solve LeetCode 99 (Recover Binary Search Tree)?

This page provides optimized solutions for LeetCode problem 99 (Recover Binary Search Tree) in Java, C++, and Python, along with a detailed explanation and an interactive code editor to test your code.

What is the time complexity of LeetCode 99 (Recover Binary Search Tree)?

The time complexity for LeetCode 99 (Recover Binary Search Tree) varies by solution. Check the detailed explanation section for specific complexities in Java, C++, and Python implementations.

Can I run code for LeetCode 99 on DevExCode?

Yes, DevExCode provides an interactive code editor where you can write, test, and run your code for LeetCode 99 in Java, C++, or Python.

Back to LeetCode Solutions