L2-006 树的遍历
给定一棵二叉树的后序遍历和中序遍历,请你输出其层序遍历的序列。这里假设键值都是互不相等的正整数。
输入格式:
输入第一行给出一个正整数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 <bits/stdc++.h> using namespace std; const int MAXN = 35; int n, in_order[MAXN], post_order[MAXN]; vector<int> ans; struct Node{ int v; int left, right; }tree[MAXN]; int Root; int build(int l1, int r1, int l2, int r2) { if(l1 > r1) return -1; int root = post_order[r2]; int p = l1; while(in_order[p] != root) { p++; } int cnt = p - l1; tree[root].left = build(l1, p-1, l2, l2+cnt-1); tree[root].right = build(p+1, r1, l2+cnt, r2-1); return root; } void bfs() { queue<int> q; q.push(Root); while(!q.empty()) { int u = q.front(); q.pop(); ans.push_back(u); if(tree[u].left != -1) { q.push(tree[u].left); } if(tree[u].right != -1) { q.push(tree[u].right); } } } int main() { cin>>n; for(int i = 0; i < n; i++) { cin>>post_order[i]; } for(int i = 0; i < n; i++) { cin>>in_order[i]; } Root = build(0, n-1, 0, n-1); bfs(); for(int i = 0; i < ans.size(); i++) { if(i != 0) { cout<<" "; } cout<<ans[i]; } cout<<endl; return 0; }
方法二指针:
#include <vector> #include <queue> #include <iostream> using namespace std; const int MAXN = 35; int n, in_order[MAXN], post_order[MAXN]; vector <int> ans; struct Node{ int v; Node *left, *right; }; Node *Root; Node * build(int l1, int r1, int l2, int r2) { if(l1 > r1) return NULL; Node *root = new Node; root->v = post_order[r2]; int p = l1; while(in_order[p] != root->v) { p++; } int cnt = p - l1; root->left = build(l1, p-1, l2, l2+cnt-1); root->right = build(p+1, r1, l2+cnt, r2-1); return root; } void bfs() { queue<Node*> q; q.push(Root); while(!q.empty()) { Node *u = q.front(); q.pop(); ans.push_back(u->v); if(u->left != NULL) { q.push(u->left); } if(u->right != NULL) { q.push(u->right); } } } int main() { cin>>n; for(int i = 0; i < n; i++) { cin>>post_order[i]; } for(int i = 0; i < n; i++){ cin>>in_order[i]; } Root = build(0, n-1, 0, n-1); bfs(); for(int i = 0; i < ans.size(); i++) { if(i != 0) { cout<<" "; } cout<<ans[i]; } cout<<endl; return 0; }