Given the post-order traversal and middle-order traversal of a binary tree, please output the sequence of its layer-order traversal. It is assumed that the key values are all positive integers that are not equal to each other.
Input format:
Enter the first line to give a positive integer N (≤30), which is the number of nodes in the binary tree. The second line gives the subsequent traversal sequence. The third line gives the in-order traversal sequence. The numbers are separated by spaces.
Output format:
Output the sequence traversed by the tree in one line. The numbers are separated by 1 space, and there must be no extra spaces at the beginning and end of the line.
Input sample:
7
2 3 1 5 7 6 4
1 2 3 4 5 6 7
Sample output:
4 1 6 3 5 7 2
Code:
import java.io.*;
import java.util.TreeMap;
public class Main {
static String[] lrd, ldr;
static TreeMap<Integer, String> map;
public static void main(String[] args) throws IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
PrintWriter out = new PrintWriter(new OutputStreamWriter(System.out));
int n = Integer.parseInt(br.readLine());// 节点个数
lrd = br.readLine().split(" ");// 后序遍历
ldr = br.readLine().split(" ");// 中序遍历
map = new TreeMap<>();
dlr(0, n - 1, 1, n - 1);
String s = "";
for (String value : map.values()) {
s += value + " ";
}
out.print(s.trim());
out.flush();
}
private static void dlr(int start, int end, int key, int root) {
// 起,止,键,根
if (start > end)
return;
int i = start;
while (i < end && !lrd[root].equals(ldr[i]))
i++;
map.put(key, lrd[root]);// 根
dlr(start, i - 1, key * 2, root - end + i - 1);// 左
dlr(i + 1, end, key * 2 + 1, root - 1);// 右
}
}