poj2255树的重建问题

#include<iostream>
#include<cstring>
#include<cstdlib>
#include<cstdio>
#include<string>
#include<sstream>
#include<vector>


using namespace std;


const int maxn = 30;




struct node {
int left;
int right;
char value;
node() {
left = -1;
right = -1;
}
};
string pre, in;
node tree[maxn];
int root = 0;
int cnt = 0;


vector<char> ans;
int index = 0;


int build(int l,int r)
{
if (l > r)return -1;


char ch = pre[cnt++];
int pos = 0;
for (int i = l; i <= r; i++)
{
if (in[i] == ch)
{
pos = i; break;
}
}
tree[index].value = ch;
tree[index].left = build(l, pos - 1);
tree[index].right = build(pos + 1, r);
ans.push_back(ch);


return index++;
}


int main()
{
//freopen("input.txt","r",stdin);

while (cin >> pre) {
cin >> in;
root = 0;
cnt = 0;
index = 0;
for (int i = 0; i < maxn; i++)tree[i].left = -1, tree[i].right = -1;
ans.clear();


root = build(0, pre.length()-1);


for (int i = 0; i < ans.size(); i++)
cout << ans[i];
cout << endl;
}
return 0;
}

猜你喜欢

转载自blog.csdn.net/PAN_Andy/article/details/61201811