We got an assignment where we need to code:
I think you should do it this manner (code is in C#, but shouldn't be very hard to convert it to Java):
//list should be sorted
public void myFunc(List list){
Queue> queue = new Queue>();
queue.Enqueue(list);
while(queue.Any()){
List l = queue.Dequeue();
int rindex = findRoot(l);
//print r or store it somewhere
Console.WriteLine(l.ElementAt(rindex));
List leftlist = l.GetRange(0, rindex);
List rightlist = l.GetRange(rindex + 1, l.Count-rindex-1);
//leftlist = list l from index 0 to r-1; rightlist = list l from index r+1 to end.
if (leftlist.Any())
{
queue.Enqueue(leftlist);
}
if (rightlist.Any())
{
queue.Enqueue(rightlist);
}
}
}
******EDIT: *********************************************
For finding the root every time you have a list of size n, do the following:
public int findRoot(List list)
{
int n = list.Count;
double h = Math.Ceiling(Math.Log(n + 1, 2)) - 1;
double totNodesInCompleteBinaryTreeOfHeighthMinusOne = Math.Pow(2, h) - 1;
double nodesOnLastLevel = n - totNodesInCompleteBinaryTreeOfHeighthMinusOne;
double nodesOnLastLevelInRightSubtree = 0;
if (nodesOnLastLevel > Math.Pow(2, h - 1))
{
nodesOnLastLevelInRightSubtree = nodesOnLastLevel - Math.Pow(2, h - 1);
}
int rindex = (int)(n - nodesOnLastLevelInRightSubtree - 1 - ((totNodesInCompleteBinaryTreeOfHeighthMinusOne - 1) / 2));
return rindex;
}