public class ConvertToPost {
private char[] preArr;
private char[] inArr;
private char[] postArr;
public ConvertToPost(char[] preArr, char[] inArr) {
this.preArr = preArr;
this.inArr = inArr;
}
//
public char[] getpostArr() throws ArrayWrongException {
Node Root = toBTree(0, preArr.length - 1, 0, inArr.length - 1);
if (preArr.length != inArr.length)
throw new ArrayWrongException(
"the length of the two array is not equal!");
postArr = new char[preArr.length];
postOrder(Root);
return postArr;
}
private Node toBTree(int preL, int preR, int inL, int inR)
throws ArrayWrongException {
Node root = new Node(preArr[preL]);
int rootIninArr = -1;
int i = -1;
for (i = inL; i <= inR; i++)
if (inArr[i] == root.key) {
rootIninArr = i;
break;
}
if (i == inR + 1)
throw new ArrayWrongException(
"the two array cant convert to a binary tree!");
int leftLen = rootIninArr - inL;
int rightLen = inR - rootIninArr;
if (leftLen != 0)
root.left = toBTree(preL + 1, preL + leftLen, inL,
rootIninArr - 1);
if (rightLen != 0)
root.right = toBTree(preL + leftLen + 1, preR, rootIninArr + 1,
inR);
return root;
}
private void postOrder(Node node) {
if (node != null) {
postOrder(node.left);
postOrder(node.right);
for (int i = 0; i < postArr.length; i++)
if ((int) postArr[i] == 0) {
postArr[i] = node.key;
break;
}
}
}
}
private char[] preArr;
private char[] inArr;
private char[] postArr;
public ConvertToPost(char[] preArr, char[] inArr) {
this.preArr = preArr;
this.inArr = inArr;
}
//
public char[] getpostArr() throws ArrayWrongException {
Node Root = toBTree(0, preArr.length - 1, 0, inArr.length - 1);
if (preArr.length != inArr.length)
throw new ArrayWrongException(
"the length of the two array is not equal!");
postArr = new char[preArr.length];
postOrder(Root);
return postArr;
}
private Node toBTree(int preL, int preR, int inL, int inR)
throws ArrayWrongException {
Node root = new Node(preArr[preL]);
int rootIninArr = -1;
int i = -1;
for (i = inL; i <= inR; i++)
if (inArr[i] == root.key) {
rootIninArr = i;
break;
}
if (i == inR + 1)
throw new ArrayWrongException(
"the two array cant convert to a binary tree!");
int leftLen = rootIninArr - inL;
int rightLen = inR - rootIninArr;
if (leftLen != 0)
root.left = toBTree(preL + 1, preL + leftLen, inL,
rootIninArr - 1);
if (rightLen != 0)
root.right = toBTree(preL + leftLen + 1, preR, rootIninArr + 1,
inR);
return root;
}
private void postOrder(Node node) {
if (node != null) {
postOrder(node.left);
postOrder(node.right);
for (int i = 0; i < postArr.length; i++)
if ((int) postArr[i] == 0) {
postArr[i] = node.key;
break;
}
}
}
}