代码可全部AC。想了挺长时间的思路,跟大家分享一下,顺便记录一下自己的学习情况。题意是已知后序和中序要求层序,首先在后序中找到最后一个结点肯定就是根结点,之后以该结点为标准将中序分为左右两部分,这两部分再根据上面的做法即可得到答案。代码如下:
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
public class Main {
static String[] level;
public static void main(String[] args) throws IOException {
BufferedReader bf = new BufferedReader(new InputStreamReader(System.in));
int num = Integer.parseInt(bf.readLine());
level = new String[num];
for (int i = 0; i < num; i++)
level[i] = "";
String[] postorder = bf.readLine().split(" ");
String[] inorder = bf.readLine().split(" ");
levelorder(postorder, inorder, 0);
String result = "";
for (int i = 0; i < level.length; i++)
result += level[i];
System.out.println(result.trim());
}
static void levelorder(String[] post, String[] in, int floor) {
String target = post[post.length - 1];
level[floor] += target + " ";
if (post.length == 1)
return;
int loc = -1;
for (int i = 0; i < post.length; i++) {
if (in[i].equals(target))
loc = i;
}
int left = loc;
int right = in.length - loc - 1;
String[] post_right = new String[right];
String[] in_right = new String[right];
String[] post_left = new String[left];
String[] in_left = new String[left];
for (int i = 0; i < left; i++) {
post_left[i] = post[i];
in_left[i] = in[i];
}
for (int i = 0; i < right; i++) {
post_right[i] = post[loc + i];
in_right[i] = in[loc + 1 + i];
}
if (left > 0 || right == 0)
levelorder(post_left, in_left, floor + 1);
if (right > 0 || left == 0)
levelorder(post_right, in_right, floor + 1);
}
}