在BinaryCharTree类中新加入构造方法,使用一个线性表先分配所有节点的空间, 再将节点链接起来, 最后并没有返回, 而是把第 0 个节点的相应值拷贝给自己.
代码:
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 if
// 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("Linking " + j + " with " + i);
break;
} else if (paraIndicesArray[i] == paraIndicesArray[j] * 2 + 2) {
tempAllNodes[j].rightChild = tempAllNodes[i];
System.out.println("Linking " + 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 constructor
运行结果:
indices 0 vs. 1
Linking 0 with 1
indices 0 vs. 2
Linking 0 with 2
indices 0 vs. 4
indices 1 vs. 4
Linking 1 with 3
indices 0 vs. 5
indices 1 vs. 5
indices 2 vs. 5
Linking 2 with 4
indices 0 vs. 12
indices 1 vs. 12
indices 2 vs. 12
indices 4 vs. 12
indices 5 vs. 12
Linking 4 with 5
Preorder visit:
A
B
D
C
E
F
In-order visit:
B
D
A
E
F
C
Post-order visit:
D
B
F
E
C
A
Process finished with exit code 0