forked from imnishant/GeeksforGeeks-Java-Solution
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathFixingTwoNodesInABST
44 lines (40 loc) · 903 Bytes
/
FixingTwoNodesInABST
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
class GfG
{
Node first, second, last, prev;
void inorder(Node root)
{
if(root == null)
return;
inorder(root.left);
if(prev != null && root.data < prev.data)
{
if(first != null)
last = root;
else
{
first = prev;
second = root;
}
}
prev = root;
inorder(root.right);
}
public Node correctBST(Node root)
{
prev = first = second = last = null;
inorder(root);
if(last == null)
{
int temp = first.data;
first.data = second.data;
second.data = temp;
}
else
{
int temp = first.data;
first.data = last.data;
last.data = temp;
}
return root;
}
}