算法思路:
通过观察栈的非递归实现中序遍历的方式可以得到:
- 一种规律是:第一个操作一定是push操作,且这个元素一定就是根结点;从第二个操作起,当上个操作为push时,则当前push进的元素为上个push的元素的左儿子,当上步操作为pop时,当前push进的元素就是pop出的元素的右儿子。所以通过模拟记录每个结点的左右儿子,从而构造出树,最后遍历树得到后序序列。
- 另一种规律是:push的序列实际上就是前序遍历的结果,而pop出的元素序列就是中序遍历的结果,从而转化成通过前序+中序求后序的问题。
Java代码:(构建树)
import java.io.*;
import java.util.Stack;
public class Main1576b {
static StreamTokenizer st = new StreamTokenizer(new BufferedReader(new InputStreamReader(System.in)));
public static int ini() throws IOException {
st.nextToken();
return (int)st.nval;
}
public static String ins() throws IOException {
st.nextToken();
return st.sval;
}
static final int N = 35;
static int []l = new int[N];
static int []r = new int[N];
static int []post = new int[N];
static int idx;
public static void main(String[] args) throws IOException {
int n = ini();
int root = 0, last = 0; // last表示父结点
boolean flag = false; //flag为false表示上次操作为push
Stack<Integer> stack = new Stack<>();
for(int i = 0; i < 2 * n; i++) {
String op = ins();
if(op.length() == 4) { // push时,取决于上一次的操做类型
int x = ini();
if(i == 0) root = x; // 第一次push的元素为二叉树根结点
else {
if(!flag) l[last] = x; // 上次仍然是push:上次push进的元素就是当前的父结点(当前为父结点的左儿子)
else r[last] = x; // 上次是pop:上次pop出的元素就是当前的父结点(当前结点为父结点的右儿子)
}
stack.add(x);
last = x; // 将父结点更新,便与下次处理
flag = false; // 标记为push操作
}else {
flag = true;
last = stack.peek();
stack.pop();
}
}
dfs(root);
System.out.print(post[0]);
for(int i = 1; i < n; i++) System.out.print(" " + post[i]);
}
public static void dfs(int root) {
if(root == 0) return; //递归出口:权值均不为0,为0时表明该结点不存在了
dfs(l[root]); // 递归左子树
dfs(r[root]); // 递归右子树
post[idx++] = root;
}
}
Java代码:(求序列)
import java.io.*;
import java.util.Stack;
public class Main {
static StreamTokenizer st = new StreamTokenizer(new BufferedReader(new InputStreamReader(System.in)));
public static int ini() throws IOException {
st.nextToken();
return (int)st.nval;
}
public static String ins() throws IOException {
st.nextToken();
return st.sval;
}
static int n, idx;
static final int N = 35;
static int[]pre = new int[N];
static int[]in = new int[N];
static int[]post = new int[N];
public static void main(String[] args) throws IOException {
n = ini();
int j = 0, k = 0;
Stack<Integer> stack = new Stack<>();
for(int i = 0; i < 2 * n; i++) {
String s = ins();
if(s.length() == 4) {
int x = ini();
stack.add(x);
pre[j++] = x;
}else in[k++] = stack.pop();
}
build(0, n - 1, 0, n - 1);
System.out.print(post[0]);
for(int i = 1; i < n; i++) System.out.print(" " + post[i]);
}
public static void build(int il, int ir, int pl, int pr) {
int root = pre[pl];
int k = 0;
for(k = il; k <= ir; k++)
if(in[k] == root) break;
if(k > ir) return; // 递归终止条件
build(il, k - 1, pl + 1, pl + 1 + k - 1 - il);
build(k + 1, ir, pl + k - il + 1, pr);
post[idx++] = root;
}
}