代码如下,错误原因未知
#include<iostream>
#include<vector>
using namespace std;
int n, in[32], post[32];
struct node{
int data;
node *left, *right;
};
vector<int> v1, v2, v;
node* create(int postL, int postR, int inL, int inR) {
if(postL > postR) return NULL;
node* root = new node;
root -> data = post[postR];
int k = inL;
while(post[postR] != in[k]) k++;
int numLeft = k - inL;
root -> left = create(postL, postL + numLeft - 1, inL, k - 1);
root -> right = create(postL + numLeft, postR - 1, k + 1, inR);
return root;
}
void toRight(node* root) {
if(root == NULL) return ;
v1.push_back(root -> data);
if(root -> right) toRight(root -> right);
else toRight(root -> left);
}
void toLeft(node* root) {
if(root == NULL) return ;
v2.push_back(root -> data);
if(root -> left) toLeft(root->left);
else toLeft(root -> right);
}
int main() {
cin >> n;
v.resize(n + 1);
for(int i = 0; i < n; i++) cin >> in[i];
for(int i = 0; i < n; i++) cin >> post[i];
node* root = create(0, n - 1, 0, n - 1);
toRight(root -> left);
toLeft(root -> right);
int size1 = v1.size(), size2 = v2.size();
int i = 0, j = 0, lst = 1, rst = 2;
while(i < size1) {
v[lst] = v1[i++];
if(lst % 2 == 1) lst += 2;
lst ++;
}
while(j < size2) {
v[rst] = v2[j++];
if(rst % 2 == 1) rst += 2;
rst ++;
}
cout << root -> data;
for(int i = 1; i <= n; i++)
if(v[i] > 0) cout << " " << v[i];
return 0;
}
AC代码
#include<iostream>
#include<vector>
#include<queue>
using namespace std;
int n, root, in[35], post[35], tree[35][2];
struct node{
int index, deepth;
};
vector<int> result[35];
void dfs(int &index,int postL, int postR, int inL, int inR) {
if(inL > inR) return ;
index = postR;
int k = inL;
while(post[postR] != in[k]) k++;
dfs(tree[index][0], postL, postL + k - inL - 1, inL, k - 1);
dfs(tree[index][1], postL + k - inL, postR - 1, k + 1, inR);
}
void bfs() {
queue<node> q;
q.push({root, 0});
while(!q.empty()) {
node top = q.front();
q.pop();
result[top.deepth].push_back(post[top.index]);
if(tree[top.index][0]) q.push({tree[top.index][0], top.deepth + 1});
if(tree[top.index][1]) q.push({tree[top.index][1], top.deepth + 1});
}
}
int main() {
cin >> n;
for(int i = 1; i <= n; i++) cin >> in[i];
for(int i = 1; i <= n; i++) cin >> post[i];
dfs(root, 1, n, 1, n);
bfs();
cout << result[0][0];
for(int i = 1; i < 35; i++) {
if(i % 2 == 1) {
for(int j = 0; j < result[i].size(); j++)
cout << " " << result[i][j];
} else {
for(int j = result[i].size() - 1; j >= 0; j--)
cout << " " << result[i][j];
}
}
return 0;
}