思路:
我们都知道,一颗二叉树,给定中序序列和任意其它序列,可以建造出整颗二叉树。树的建造有两种方式,一种是静态,一种是动态。
AC 代码(动态):
#include<bits/stdc++.h>
using namespace std;
const int N = 100,INF = 0x3f3f3f3f;
struct Tree {
int val;
Tree *l = NULL;
Tree *r = NULL;
Tree(int x) {
val = x;
}
}*root;
int n,a[N],b[N],len;
int ans[N];
void builtTree(int l,int r,int &t,Tree *&root) {
int pos = -1;
for(int i = l; i <= r; i ++) {
if(a[t] == b[i]) {
pos = i;
break;
}
}
if(pos == -1) return ;
root = new Tree(b[pos]);
t --;
if(pos < r) {
builtTree(pos + 1,r,t,root->r);
}
if(l < pos) {
builtTree(l,pos - 1,t,root->l);
}
}
void bfs() {
queue<Tree*> q;
q.push(root);
while(!q.empty()) {
Tree* tmp = q.front();
q.pop();
ans[len ++] = tmp->val;
if(tmp->l != NULL)
q.push(tmp->l);
if(tmp->r != NULL)
q.push(tmp->r);
}
}
int main() {
cin>>n;
for(int i = 1; i <= n; i ++) {
cin>>a[i];
}
for(int j = 1; j <= n; j ++) {
cin>>b[j];
}
builtTree(1,n,n,root);
bfs();
for(int i = 0; i < len; i ++) {
if(i == len - 1)
cout<<ans[i];
else cout<<ans[i]<<" ";
}
return 0;
}
AC 代码(静态):
这中按完全二叉树建树的方式很费空间,最好不要按这种方式设置左右子树,但是这道题数据范围小,可以用。
#include<bits/stdc++.h>
using namespace std;
const int N = 10000,INF = 0x3f3f3f3f;
struct Tree {
int val;
int l,r;
}tree[N];
int n,a[N],b[N],len;
int ans[N];
void builtTree(int l,int r,int &t,int idx) {
int pos = -1;
for(int i = l; i <= r; i ++) {
if(a[t] == b[i]) {
pos = i;
break;
}
}
if(pos == -1) return ;
tree[idx].val = b[pos];
tree[idx].l = 2 * idx;
tree[idx].r = 2 * idx + 1;
t --;
if(pos < r) {
builtTree(pos + 1,r,t,2*idx+1);
}
if(l < pos) {
builtTree(l,pos - 1,t,2*idx);
}
}
void bfs() {
queue<Tree> q;
q.push(tree[1]);
while(!q.empty()) {
Tree tmp = q.front();
q.pop();
ans[len ++] = tmp.val;
if(tree[tmp.l].val != 0)
q.push(tree[tmp.l]);
if(tree[tmp.r].val != 0)
q.push(tree[tmp.r]);
}
}
int main() {
cin>>n;
for(int i = 1; i <= n; i ++) {
cin>>a[i];
}
for(int j = 1; j <= n; j ++) {
cin>>b[j];
}
builtTree(1,n,n,1);
bfs();
for(int i = 0; i < len; i ++) {
if(i == len - 1)
cout<<ans[i];
else cout<<ans[i]<<" ";
}
return 0;
}