给定一棵二叉树的后序遍历和中序遍历,请你输出其层序遍历的序列。这里假设键值都是互不相等的正整数。
输入格式:
输入第一行给出一个正整数N(<=30),是二叉树中结点的个数。第二行给出其后序遍历序列。第三行给出其中序遍历序列。数字间以空格分隔。
输出格式:
在一行中输出该树的层序遍历的序列。数字间以1个空格分隔,行首尾不得有多余空格。
输入样例:
7 2 3 1 5 7 6 4 1 2 3 4 5 6 7
输出样例:
4 1 6 3 5 7 2
分析:根据前序遍历、中序遍历、后序遍历的特点,我们会发现前序遍历是根->左子树->右子树,而后序遍历是后序左子树->后序右子树->根.
我们会发现前序遍历和后续遍历是有联系的,每次找到根节点,然后在对左子树、右子树进行遍历。
#include<cstdio> #include<cmath> #include<iostream> #include<algorithm> #include<vector> #include<stack> #include<cstring> #include<queue> #include<set> #include<string> #include<map> #include <time.h> #define PI acos(-1) using namespace std; typedef long long ll; typedef double db; const int maxn = 1e4; const ll maxm = 1e7; const int mod = 1000000009; const int INF = 0x3f3f3f; const ll inf = 1e14 + 5; const db eps = 1e-9; int qian[maxn], zhong[maxn], hou[maxn]; int n; void dfs(int root, int start, int endd, int index) { if (start>endd) return; int i=start; while(i<endd&&zhong[i]!=hou[root]) i++; qian[index]=hou[root]; dfs(root-1-endd+i, start, i-1, 2*index+1); dfs(root-1, i+1, endd, 2*index+2); } void solve() { scanf("%d", &n); memset(qian, 0, sizeof(qian)); memset(hou, 0, sizeof(hou)); memset(zhong ,0, sizeof(zhong)); for (int i = 0; i < n; i++) { scanf("%d", hou+i); } for (int i = 0; i < n; i++) { scanf("%d", zhong+i); } dfs(n-1, 0, n-1, 0); int cnt=0; for (int i = 0; i < maxn; i++) { if (qian[i]) { if (cnt) printf(" "); printf("%d", qian[i]); cnt++; } } } int main() { int t = 1; while(t--) solve(); return 0; }
类似:
L2-011. 玩转二叉树
给定一棵二叉树的中序遍历和前序遍历,请你先将树做个镜面反转,再输出反转后的层序遍历的序列。所谓镜面反转,是指将所有非叶结点的左右孩子对换。这里假设键值都是互不相等的正整数。
输入格式:
输入第一行给出一个正整数N(<=30),是二叉树中结点的个数。第二行给出其中序遍历序列。第三行给出其前序遍历序列。数字间以空格分隔。
输出格式:
在一行中输出该树反转后的层序遍历的序列。数字间以1个空格分隔,行首尾不得有多余空格。
输入样例:
7 1 2 3 4 5 6 7 4 1 3 2 6 5 7
输出样例:
4 6 1 7 5 3 2
#include<cstdio> #include<cmath> #include<iostream> #include<algorithm> #include<vector> #include<stack> #include<cstring> #include<queue> #include<set> #include<string> #include<map> #include <time.h> #define PI acos(-1) using namespace std; typedef long long ll; typedef double db; const int maxn = 1e5; const ll maxm = 1e7; const int mod = 1000000009; const int INF = 0x3f3f3f; const ll inf = 1e14 + 5; const db eps = 1e-9; int qian[maxn], zhong[maxn], hou[maxn]; int n; void dfs(int root, int start, int endd, int index) { if (start>endd) return; int i=start; while(i<endd&&zhong[i]!=qian[root]) i++; hou[index] = qian[root]; dfs(root+1, start, i-1, 2*index+2); dfs(root-start+i+1, i+1, endd, 2*index+1); } void solve() { scanf("%d", &n); memset(qian, 0, sizeof(qian)); memset(hou, 0, sizeof(hou)); memset(zhong ,0, sizeof(zhong)); for (int i = 0; i < n; i++) { scanf("%d", zhong+i); } for (int i = 0; i < n; i++) { scanf("%d", qian+i); } dfs(0, 0, n-1, 0); int cnt=0; for (int i = 0; i < maxn; i++) { if (hou[i]) { if (cnt) printf(" "); printf("%d", hou[i]); cnt++; } } } int main() { int t = 1; while(t--) solve(); return 0; }