package test_kepler;
public class TreefromA {
int totalNum ;
Node[] treeA;
int[] array1 = new int[]{1,2,34,45,90};
class Node
{
int value;
Node leftChild ;
Node rightChild;
public boolean isVisted;
public Node()
{
value =0;
leftChild=null;
rightChild=null;
isVisted = false;
}
public void setLeftChild(Node lc)
{
this.leftChild = lc;
}
public void setrightChild(Node rc)
{
this.rightChild = rc;
}
public void print()
{
System.out.print(this.value +" ~~ ");
}
};
public TreefromA(int [] a)
{
totalNum = a.length;
treeA = new Node[totalNum];
for(int i = 0;i<totalNum;++i)
{
treeA[i] = new Node();
System.out.println(a[i]+"==>");
treeA[i].value = a[i];
}
buildTree();
BFS();
}
//return is the whole layer - 1;
public int getLayer(int array_length)
{
int i = 1;
while(array_length>0)
{
array_length = array_length<<i;
++i;
}
return i;
}
//get ceiling
int getCeiling(double i)
{
int result = (int)i;
int k = result +1;
System.out.println(i+"-->"+k);
return (result +1);
}
//get parentnum
int getParent(int i)
{
if(i <=0) {System.out.println("this is wrong for finding father");return -1;}
double ik = i/2;
return getCeiling(ik)-1;
}
int power(int base,int i)
{
if(i == 0) return 1;
else
{
return base * power(base,i-1);
}
}
//!!!!
int power2(int base,int i)
{
int result = 1;
if(i ==0) return 1;
else
{
for(int j = 0;j<i;++j)
{
result = result*base;
}
System.out.println("power2 = "+result);
return result;
}
}
public void buildTree()
{
int runtime = 0;
for(int i = 1;i <= getLayer(totalNum)-1;++i)
{
for(int j = power(2,i)-1;j<=(power(2,i)-1)*2;++j)
{
System.out.println("j = "+j);
if(j%2 ==1)
{
int f =getParent(j);
System.out.println("f = "+f);
treeA[f].print();
treeA[getParent(j)].setLeftChild(treeA[j]);
}
else
{
treeA[getParent(j)].setrightChild(treeA[j]);
}
runtime++;
if(runtime == totalNum-1)
{
return ;
}
}
}
}
//TEST FUNCTION
void BFS()
{
qbytwostc testq = new qbytwostc<Node>();
testq.enQueue(treeA[0]);
while(!testq.isEmpty())
{
Node head = (Node) testq.dequeue();
if(head.isVisted == false)
head.print();
if(head.rightChild!=null && head.rightChild.isVisted == false)
{
testq.enQueue(head.rightChild);
}
if(head.leftChild!=null && head.leftChild.isVisted == false)
{
testq.enQueue(head.leftChild);
}
}
}
public static void main(String[] args) {
//int a[] = {1,2,34,45,90};
int[] array = new int[]{1,2,34,45,90,9090};
TreefromA ta = new TreefromA(array);
/*
for(int i = 0;i<10;++i)
{
System.out.println(i+"->"+ta.power(2, i)+" --->>> "+ ta.power2(2, i));
}*/
}
}