I am solving one of the HackerEarth problem . And problem statement is as follows,
Given a complete binary tree with N nodes and each node have an distinct integer ai attached with it, find the minimum number of swaps you can make to convert the binary tree into binary search tree. In one swap, you can select any two nodes and swap their values.
You will be given the array representation of the binary tree. Root of the tree will be at a[1] Left child of root will be at a[2] and right child of root will be at a3. Left child of node at array position k will be at a[2∗k] and right child of node at array position k will be at a[2∗k+1].
Question is how to convert given array into in-order array of the tree.I tried following code. On web i did't found any link.
static void inOrderArr(int destIndex,int index, int[] source, int[] dest) {
int leftIndex = (index ) * 2;
int rightIndex = (((index ) * 2) + 1);
if(leftIndex<source.length){
inOrderArr(destIndex,leftIndex, source,dest);
}
System.out.println(index);
dest[destIndex++] = source[index-1];
if(rightIndex<source.length){
inOrderArr(destIndex,rightIndex, source,dest);
}
}
I tried the following solution and it worked.
private static void inorderTraversal(int array[], int pos, Node[] nodes) {
if (pos >= array.length) {
return;
}
inorderTraversal(array, 2 * pos + 1, nodes);
nodes[Node.count] = new Node(array[pos], Node.count);
Node.count++;
inorderTraversal(array, 2 * pos + 2, nodes);
}
Here is the Node type declaration
static private class Node implements Comparable<Node> {
private static int count = 0;
public Node(int value) {
this.value = value;
}
public Node(int value, int position) {
this(value);
this.position = position;
}
private int value;
private int position;
private boolean visited;
public boolean isVisited() {
return visited;
}
public void markVisited() {
visited = true;
}
@Override
public int compareTo(Node o) {
if (this.value >= o.value) {
return 1;
}
return -1;
}
}