Jul 4, 2024
firstViolation = null
, secondViolation = null
firstViolation
= previous node.secondViolation
= current node.Node
class Node {
int value;
Node left;
Node right;
public Node(int val) {
this.value = val;
}
}
public class TwoNodeSwap {
Node first = null;
Node second = null;
Node previous = null;
public void helper(Node root) {
inOrderTraversal(root);
int temp = first.value;
first.value = second.value;
second.value = temp;
}
private void inOrderTraversal(Node node) {
if (node == null) return;
inOrderTraversal(node.left);
if (previous != null && previous.value > node.value) {
if (first == null) first = previous;
second = node;
}
previous = node;
inOrderTraversal(node.right);
}
}