储存二叉树
package datastructure.queue;
/**
* Circle Object queue.
*
* @author Michelle Min MitchelleMin@163.com
*/
public class CircleObjectQueue {
/**
* The total space. One space can never be used.
*/
public static final int TOTAL_SPACE = 10;
/**
* The data.
*/
Object[] data;
/**
* The index of the head.
*/
int head;
/**
* The index of the tail.
*/
int tail;
/**
*
* The constructor
*
*/
public CircleObjectQueue(){
data = new Object[TOTAL_SPACE];
head = 0;
tail = 0;
}//Of the first constructor
/**
*
* Enqueue.
*
* @param paraValue
* The value of the new node.
*
*/
public void enqueue(Object paraValue){
if ((tail + 1) % TOTAL_SPACE == head){
System.out.println("Queue full.");
return;
}//Of if
data[tail % TOTAL_SPACE] = paraValue;
tail++;
}//Of enqueue
/**
*
* Dequeue.
*
* @return The value at the head.
*
*/
public Object dequeue(){
if (head == tail){
System.out.println("No element in the queue");
return null;
}//Of if
Object resultValue = data[head];
head++;
return resultValue;
}//Of dequeue
/**
*
* Overrides the method claimed in Object, the superclass of any class.
*
*/
public String toString(){
String resultString = "";
if (head == tail){
return "empty";
}//Of if
for (int i = head; i < tail; i++){
resultString += data[i % TOTAL_SPACE] +", ";
}//Of for i
return resultString;
}//Of toString
/**
*
* The entrance of the program.
*
* @param args
* Not used now.
*
*/
public static void main(String args[]){
CircleObjectQueue tempQueue= new CircleObjectQueue();
}//Of main
}//Of CircleObjectQueue
/**
*
* Convert the tree to data arrays, including a char array and and an int array.
* The result are stored in two member variables.
*
* @see #valuesArray
* @see #indicesArray
*
*/
public void toDataArrays(){
//Initialize arrays.
int tempLength = getNumNodes();
valuesArray = new char[tempLength];
indicesArray = new int[tempLength];
int i = 0;
//Traverse and convert at the same time.
CircleObjectQueue tempQueue = new CircleObjectQueue();
tempQueue.enqueue(this);
CircleIntQueue tempIntQueue = new CircleIntQueue();
tempIntQueue.enqueue(0);
BinaryCharTree tempTree = (BinaryCharTree) tempQueue.dequeue();
int tempIndex = tempIntQueue.dequeue();
while (tempTree != null){
valuesArray[i] = tempTree.value;
indicesArray[i] = tempIndex;
i++;
if (tempTree.leftChild != null){
tempQueue.enqueue(tempTree.rightChild);
tempIntQueue.enqueue(tempIndex * 2 + 2);
}//Of if
tempTree = (BinaryCharTree) tempQueue.dequeue();
tempIndex = tempIntQueue.dequeue();
}//Of While
}//Of toDataArrays