题目链接
题目大意:
根据前序,中序遍历输出后序遍历。
分析:
之前做过了一道和这个很相似的题目,所以很快就写了出来。这是用结构体写的。
#include <bits/stdc++.h>
using namespace std;
const int maxn = 50;
typedef struct Bitnode{
char data;
struct Bitnode *left, *right;
}Bitnode, *Bitree;
Bitree build(char *pre, char *in, int n) {
if(n<=0) return nullptr;
auto bitree = new Bitnode();
char *p = in;
while(*p!=*pre) p++;
bitree->data = *p;
int len = p-in;
bitree->left = build(pre+1, in, len);
bitree->right = build(pre+len+1,p+1,n-len-1);
return bitree;
}
void post(Bitree root) {
if(root) {
post(root->left);
post(root->right);
cout << root->data;
}
}
void delete_(Bitree &bitree) {
if(!bitree) return;
if(bitree->left) delete_(bitree->left);
if(bitree->right) delete_(bitree->right);
delete(bitree);
bitree = nullptr;
}
int main() {
freopen("i.txt", "r", stdin);
// freopen("o.txt", "w", stdout);
char pre[maxn], in[maxn];
while(cin >> pre >> in) {
int len;
for(len=0; pre[len]; len++);
Bitree root = build(pre,in,len);
post(root);
delete_(root);
cout << endl;
}
}
数值模拟二叉树又写了一遍:
#include <bits/stdc++.h>
using namespace std;
const int maxn = 50;
char pre[maxn], in[maxn];
int Left[maxn], Right[maxn], pre_num[maxn], in_num[maxn];
int Build(int l1,int r1,int l2,int r2) {
if(l1>r1) return 0;
int root = pre_num[l1];
int p = l2;
while(in_num[p]!=root) p++;
int len = p-l2;
Left[root] = Build(l1+1,l1+len,l2,p-1);
Right[root] = Build(l1+len+1,r1,p+1,r2);
return root;
}
void Post(int root) {
if(Left[root]) Post(Left[root]);
if(Right[root]) Post(Right[root]);
cout << (char)(root+'A'-1);
}
int main() {
freopen("i.txt","r",stdin);
freopen("o.txt","w",stdout);
while(cin >> pre >> in) {
memset(Left,0,sizeof(Left));
memset(Right,0,sizeof(Right));
memset(pre_num,0,sizeof(pre_num));
memset(in_num,0,sizeof(in_num));
int len;
for(len = 0; pre[len]; len++);
for(int i = 0; i < len; i++) {
pre_num[i] = pre[i] - 'A' + 1;
in_num[i] = in[i] - 'A' + 1;
}
Build(0,len-1,0,len-1);
Post(pre_num[0]);
cout << endl;
}
}