99 Recover Binary Search Tree
99. Recover Binary Search Tree
1. Question
2. Implementation
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;
}
}
}3. Time & Space Complexity
Last updated