inorder 无序
implemented 实施
recursive 递归
unique 唯一的确定的
generated 产生
sequence 序列
operations 运行 实施
postorder traversal sequence 后序遍历序列
题意:给出中序遍历,得到后序遍历结果
观察Push的顺序为先序遍历,Pop的顺序为中序遍历,先根据其顺序建立数组先序遍历数组pre[]和中序遍历数组in[]
vector<int> pre, in, post;
void postorder(int root, int start, int end) {
if (start > end) return;
int root_index = 0;
while (root_index <= end && in[root_index] != pre[root]) root_index++; //找子树的根节点
postorder(root + 1, start, root_index - 1); //左子树建树
postorder(root + 1 + root_index - start, root_index + 1, end); //右子树建树
post.push_back(pre[root]);
}
int main() {
stack<int> sta; //存数,根据输入的中序遍历找到前序遍历
int N;
scanf("%d", &N);
char ch[5];
while (~scanf("%s", &ch)) { //空格结束
if (strlen(ch) == 4) {
int num;
scanf("%d", &num);
pre.push_back(num);
sta.push(num);
}
else {
in.push_back(sta.top());
sta.pop();
if (in.size() == N) break;
}
}
postorder(0, 0, N - 1);
for (int i = 0; i < N; i++) { //输出后续遍历
if (i != N - 1) printf("%d ", post[i]);
else printf("%d", post[i]);
}
return 0;
}
本文详细介绍了如何通过递归方式将给定的中序遍历序列转换为后序遍历,通过先序遍历数组和中序遍历数组的对应关系,逐步构建并输出后序遍历结果。通过实例代码展示了如何在C++中实现这一过程。
333

被折叠的 条评论
为什么被折叠?



