Binary Tree Traversals HDU - 1710(二叉树已知前序中序求后序)
我们知道二叉树是指最多有两个孩子的树,分别为左孩子和右孩子,或者左子树和右子树。根据根节点以及左右子树的访问顺序不同,对二叉树的遍历分别有先序遍历、中序遍历和后序遍历。
现在给定一棵树的先序遍历和中序遍历,试求出其后序遍历。
#define _CRT_SECURE_NO_WARNINGS #include<iostream> #include<cstring> #include<stdio.h> #include<algorithm> #include<map> #include<queue> #include<set> #include <sstream> #include<vector> #include<cmath> using namespace std; #define ll long long int a[1000009] = {}; int b[1000009] = {}; int c[1000009] = {}; int step = 1; void buil(int L1,int R1,int L2,int R2)//a中,b前 { if (L1 > R1||L2>R2) return; int p = L1; while (a[p] != b[L2])//找到当前的根节点 p++; buil(L1, p - 1, L2 + 1, L2 + p-L1);//遍历左子树 buil(p + 1, R1, L2 +p-L1+1, R2);//遍历右子树 c[step]= b[L2];//递归记录 step++; } int main() { int n; while (~scanf("%d", &n)) { step = 1; memset(a, 0, sizeof(a)); memset(b, 0, sizeof(b)); memset(c, 0, sizeof(c)); for (int i = 0; i < n; i++) { cin >> b[i]; } for (int i = 0; i < n; i++) { cin >> a[i]; } buil(0, n - 1, 0, n - 1); for (int i = 1; i < step; i++) { if (i == 1) cout << c[i]; else cout << " " << c[i]; } cout << endl; } }