满二叉树的先序序列存储在数组中,设计一个算法将其转换成后序遍历
先序序列:A B D H I E J K C F L M G N O
后序序列:H I D J K E B L M F N O G C A
Transfer函数参数说明:
pre就是先序序列数组,f1,l1分别是先序序列的第一个和最后一个元素;
post就是后序序列数组,f2,l2分别是后序序列的第一个和最后一个元素;
核心:
每一次将【待处理宽度的】先序数组的第一个元素放到后序数组的最后。
public class Mian {
public static int width(int first, int end) {
return (end - first) / 2;
}
public static void Transfer(
String[] pre, int f1, int l1,
String[] post, int f2, int l2) {
if (f1 <= l1) {
post[l2] = pre[f1];
Transfer(pre, f1 + 1, f1 + width(f1, l1), post, l2 - 2 * width(f2, l2), l2 - 1 - width(f2, l2));
Transfer(pre, f1 + 1 + width(f1, l1), f1 + 2 * width(f1, l1), post, l2 - width(f2, l2), l2 - 1);
}
}
public static void main(String[] args) {
int nums = 15;
String[] pre = {"A", "B", "D", "H", "I", "E", "J", "K", "C", "F", "L", "M", "G", "N", "O"};
String[] post = {"", "", "", "", "", "", "", "", "", "", "", "", "", "", "", ""};
Transfer(
pre, 0, nums - 1,
post, 0, nums - 1);
for (int i = 0; i < post.length; ++i) {
System.out.print(post[i] + " ");
}
System.out.println();
}
}