1.代码:在昨天的代码里加上第二种构造方法,代码如下:
/**
*********************
* The second constructor. The parameters must be correct since no validity
* check is undertaken.
*
* @param paraDataArray The array for data.
* @param paraIndicesArray The array for indices.
*********************
*/
public BinaryCharTree(char[] paraDataArray, int[] paraIndicesArray) {
// Step 1.Use a sequential list to store all nodes.
int tempNumNodes = paraDataArray.length;// 总结点数.
BinaryCharTree[] tempAllNodes = new BinaryCharTree[tempNumNodes];// 存储树结点的数组
for (int i = 0; i < tempNumNodes; i++) {
tempAllNodes[i] = new BinaryCharTree(paraDataArray[i]);//建立每个结点
} // Of for i
// Step 2.Link these nodes.
for (int i = 1; i < tempNumNodes; i++) {
for (int j = 0; j < i; j++) {
System.out.println("indices " + paraIndicesArray[j] + " vs. " + paraIndicesArray[i]);
if (paraIndicesArray[i] == paraIndicesArray[j] * 2 + 1) {// 左孩子
tempAllNodes[j].leftChild = tempAllNodes[i];
System.out.println("Link " + j + " with " + i);
} else if (paraIndicesArray[i] == paraIndicesArray[j] * 2 + 2) {// 右孩子
tempAllNodes[j].rightChild = tempAllNodes[i];
System.out.println("Link " + j + " with " + i);
break;
} // Of if
} // Of for j
} // Of for i
// step 3.The root is the first node.
value = tempAllNodes[0].value;
leftChild = tempAllNodes[0].leftChild;
rightChild = tempAllNodes[0].rightChild;
}// Of the second constructor
main函数:
public static void main(String args[]) {
BinaryCharTree tempTree = 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));
tempTree.toDataArraysObjectQueue();
System.out.println("Only object queue.");
System.out.println("The values are: " + Arrays.toString(tempTree.valuesArray));
System.out.println("The indices are: " + Arrays.toString(tempTree.indicesArray));
char[] tempCharArray = {'A', 'B', 'C', 'D', 'E', 'F'};
int[] tempIndicesArray = {0, 1, 2, 4, 5, 12};
BinaryCharTree tempTree2 = new BinaryCharTree(tempCharArray, tempIndicesArray);
System.out.println("\r\nPreorder visit:");
tempTree2.preOrderVisit();
System.out.println("\r\nIn-order visit:");
tempTree2.inOrderVisit();
System.out.println("\r\nPost-order visit:");
tempTree2.postOrderVisit();
}// Of main
2.运行结果:
3.总结:
建立二叉树:相当于存储二叉树的逆过程,将结点保存到一个线性表中 ,然后从根节点的下一个结点开始,找到其父节点,并判断其为左孩子还是右孩子,并连接,最终得到二叉树。