1.已知前序和中序序列,求后序序列?
private static ArrayList<Character> list = new ArrayList<>();
public static void getPostOrder(char[] pre, int preL, int preR, char[] in, int inL, int inR) {
if (preL > preR || inL > inR)
return;
char temp = pre[preL];
int i = inL;
while (in[i] != temp && i <= inR)
i++;
getPostOrder(pre, preL + 1, preL + i - inL, in, inL, i - 1);
getPostOrder(pre, preR - inR + i + 1, preR, in, i + 1, inR);
list.add(temp);
}
public static void PostOrder(char[] pre, char[] in) {
int preR = pre.length - 1;
int inR = in.length - 1;
getPostOrder(pre, 0, preR, in, 0, inR);
}
2.已知中序和后序序列,求前序序列?
private static ArrayList<Character> list = new ArrayList<>();
public static void getPreOrder(char[] in, int inL, int inR, char[] post, int postL, int postR) {
if (inL > inR || postL > postR)
return;
char temp = post[postR];
int i = inL;
while (in[i] != temp && i <= inR)
i++;
list.add(temp);
getPreOrder(in, inL, i - 1, post, postL, i - 1 - inL + postL);
getPreOrder(in, i + 1, inR, post, postR - inR + i, postR - 1);
}
public static void PreOrder(char[] in, char[] post) {
int inR = in.length - 1;
int postR = post.length - 1;
getPreOrder(in, 0, inR, post, 0, postR);
}