99. Recover Binary Search Tree
Two elements of a binary search tree (BST) are swapped by mistake.
Recover the tree without changing its structure.
A solution using O(n) space is pretty straight forward. Could you devise a constant space solution?
class Solution {
public void recoverTree(TreeNode root) {
Stack<TreeNode> stack = new Stack<>();
TreeNode curNode = root;
TreeNode preNode = null, firstNode = null, secondNode = null;
while (curNode != null || !stack.isEmpty()) {
if (curNode != null) {
stack.push(curNode);
curNode = curNode.left;
}
else {
curNode = stack.pop();
if (preNode != null && preNode.val > curNode.val) {
if (firstNode == null) {
firstNode = preNode;
}
secondNode = curNode;
}
preNode = curNode;
curNode = curNode.right;
}
}
if (firstNode != null && secondNode != null) {
int temp = firstNode.val;
firstNode.val = secondNode.val;
secondNode.val = temp;
}
}
}
class Solution {
public void recoverTree(TreeNode root) {
TreeNode[] nodes = new TreeNode[3];
inorderTraverse(root, nodes);
int temp = nodes[1].val;
nodes[1].val = nodes[2].val;
nodes[2].val = temp;
}
public void inorderTraverse(TreeNode node, TreeNode[] nodes) {
if (node == null) {
return;
}
inorderTraverse(node.left, nodes);
TreeNode preNode = nodes[0];
if (preNode != null && preNode.val >= node.val) {
if (nodes[1] == null) {
nodes[1] = preNode;
}
nodes[2] = node;
}
nodes[0] = node;
inorderTraverse(node.right, nodes);
}
}
3. Time & Space Complexity