1.二叉树的存储
代码:
package tree;
import java.util.Arrays;
import tree.BinaryCharTree;
public class CircleObjectQueue2 {
// 广度优先遍历得到的结点值
char[] valuesArray;
// 完全二叉树的索引
int[] indicesArray;
// 将树转换为数据数组,包括一个 char 数组和一个 int 数组。 结果存储在两个成员变量中。
public void toDataArrays() {
// 初始化数组 ????
/*int tempLength = getNumNodes();
valuesArray = new char[tempLength];
indicesArray = new int[tempLength];
int i = 0;
*/
// 同时遍历和转换
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.leftChild);
tempIntQueue.enqueue(tempIndex * 2 + 1);
} // Of if
if (tempTree.rightChild != null) {
tempQueue.enqueue(tempTree.rightChild);
tempIntQueue.enqueue(tempIndex * 2 + 2);
} // Of if
tempTree = (BinaryCharTree) tempQueue.dequeue();
tempIndex = tempIntQueue.dequeue();
} // Of while
}// Of toDataArrays
// main
public static void main(String args[]) {
// CircleObjectQueue tempQueue = new CircleObjectQueue();
BinaryCharTree tempTree = BinaryCharTree.manualConstructTree();
System.out.println("\r\nPreorder visit:");
tempTree.preOrderVisit();
System.out.println("\r\nIn-order visit:");
tempTree.inOrderVisit();
System.out.println("\r\nPost-order visit:");
tempTree.postOrderVisit();
System.out.println("\r\n\r\nThe depth is: " + tempTree.getDepth());
System.out.println("The number of nodes is: " + tempTree.getNumNodes());
tempTree.toDataArrays();
System.out.println("The values are: " + Arrays.toString(tempTree.valuesArray));
System.out.println("The indices are: " + Arrays.toString(tempTree.indicesArray));
}// Of main
}
2.总结
人已经懵了,在调用其他类的函数中出现了点问题,例如56行中,源代码是没有加上右边BinaryCharTree类的名,如果不在等号右边加上BinaryCharTree这个类的名时,会报错没定义这个函数。再例如16行初始化数组时,18行好像没运行与不运行都没影响最后的结果?因为这一行调用getNumNodes这个函数时,也有点问题,同样是显示在CircleObjectQueue2这个类中没有定义这个函数。今天主要对这篇代码中,调用其他类中的函数没怎么搞明白,有些可以调用成功,有些调用不成功,再加上计算遍历以及编号,懵逼了。。。如果说将22天的代码,直接全部放进21天的代码中,其也是可以直接运行的,毕竟其调用的函数全在21天里面创建的。。。