-
Notifications
You must be signed in to change notification settings - Fork 15
Expand file tree
/
Copy pathBT_Problem_22.java
More file actions
97 lines (76 loc) · 2.53 KB
/
Copy pathBT_Problem_22.java
File metadata and controls
97 lines (76 loc) · 2.53 KB
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
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
package trees.binaryTree;
import java.util.*;
/*
Problem Title :- Find minimum swaps required to convert a Binary tree into BST
*/
public class BT_Problem_22 {
static class Pair{
int first, second;
Pair(int a, int b){
first = a;
second = b;
}
}
// Inorder Traversal of Binary Tree
static void inorder(int[] a, Vector<Integer> v, int n, int index) {
// if index is greater or equal to vector size
if(index >= n)
return;
inorder(a, v, n, 2 * index + 1);
// push elements in vector
v.add(a[index]);
inorder(a, v, n, 2 * index + 2);
}
// Function returns the
// minimum number of swaps
// required to sort the arrays.array
// Refer :
// https://www.geeksforgeeks.org/minimum-number-swaps-required-sort-array/
public static int minSwaps(Vector<Integer> arr) {
int n = arr.size();
ArrayList < Pair > arrpos = new ArrayList <> ();
for (int i = 0; i < n; i++)
arrpos.add(new Pair(arr.get(i), i));
// Sort the arrays.array by arrays.array element values to
// get right position of every element as the
// elements of second arrays.array.
arrpos.sort(Comparator.comparingInt(o -> o.first));
// To keep track of visited elements. Initialize
// all elements as not visited or false.
Boolean[] vis = new Boolean[n];
Arrays.fill(vis, false);
// Initialize result
int ans = 0;
// Traverse arrays.array elements
for (int i = 0; i < n; i++) {
// already swapped and corrected or
// already present at correct pos
if (vis[i] || arrpos.get(i).first == i)
continue;
// find out the number of node in
// this cycle and add in ans
int cycle_size = 0;
int j = i;
while (!vis[j]) {
vis[j] = true;
// move to next node
j = arrpos.get(j).second;
cycle_size++;
}
// Update answer by adding current cycle.
if(cycle_size > 0) {
ans += (cycle_size - 1);
}
}
// Return result
return ans;
}
// Driver code
public static void main(String[] args) {
int[] a = { 5, 6, 7, 8, 9, 10, 11 };
int n = a.length;
Vector<Integer> v = new Vector<>();
inorder(a, v, n, 0);
System.out.println(minSwaps(v));
}
}