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.
- Initialize three pointers
first
,middle
, andlast
tonull
. Also, initialize aprev
pointer tonull
. - Perform an in-order traversal of the BST.
- 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
isnull
, setfirst
toprev
andmiddle
to the current node. - If
first
is notnull
, setlast
to the current node.
- If
- After traversal, swap the values of
first
andlast
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.