实现这个自定义遍历的思路就是直接层序遍历存入一个数组,然后对这个数组自定义排序,然后输出就行了
#include<iostream>
#include<vector>
#include<map>
#include<string>
#include<cstring>
#include<cstdio>
#include<algorithm>
#include<set>
#include<queue>
using namespace std;
const int maxn = 30;
int post[maxn], in[maxn];
struct node
{
int data, level, index;
node* left, * right;
};
vector<node*>v;
bool cmp(node* a, node* b) {
if (a->level != b->level) return a->level < b->level;
if (a->level % 2 == 0) return a->index > b->index;
return a->index < b->index;
}
node* create(int postl, int postr, int inl, int inr,int index,int level)
{
if (postl > postr)
return NULL;
node* root = new node;
root->data = post[postr];
root->index = index;
root->level = level;
int i;
for (i = inl; i <= inr; i++)
{
if (in[i] == post[postr])
break;
}
int numleft = i - inl;
root->left = create(postl, postl + numleft - 1, inl, i - 1,index*2+1,level+1);
root->right = create(postl + numleft, postr - 1, i + 1, inr,index*2+2,level+1);
return root;
}
void bfs(node *root)
{
queue<node*>q;
q.push(root);
v.push_back(root);
while (!q.empty())
{
node* now = q.front();
q.pop();
if (now->left!=NULL)
{
q.push(now->left);
v.push_back(now->left);
}
if (now->right!=NULL)
{
q.push(now->right);
v.push_back(now->right);
}
}
}
int main()
{
node* T; int n;
cin >> n;
for (int i = 0; i < n; i++)
cin >> in[i];
for (int i = 0; i < n; i++)
cin >> post[i];
T = create(0, n - 1, 0, n - 1,0,0);
bfs(T);
sort(v.begin(), v.end(), cmp);
for (int i = 0; i < v.size(); i++) {
if (i != 0) cout << " ";
cout << v[i]->data;
}
}
当然可以不用死套模板,更简洁的写法如下
#include<iostream>
#include<vector>
#include<map>
#include<string>
#include<cstring>
#include<cstdio>
#include<algorithm>
#include<set>
#include<queue>
using namespace std;
const int maxn = 30;
int post[maxn], in[maxn];
struct node
{
int data, level, index;
node* left, * right;
};
vector<node*>v;
bool cmp(node* a, node* b) {
if (a->level != b->level) return a->level < b->level;
if (a->level % 2 == 0) return a->index > b->index;
return a->index < b->index;
}
void* create(int postl, int postr, int inl, int inr,int index,int level)
{
if (postl > postr)
return NULL;
node* root = new node;
root->data = post[postr];
root->index = index;
root->level = level;
int i;
for (i = inl; i <= inr; i++)
{
if (in[i] == post[postr])
break;
}
v.push_back(root);
int numleft = i - inl;
create(postl, postl + numleft - 1, inl, i - 1,index*2+1,level+1);
create(postl + numleft, postr - 1, i + 1, inr,index*2+2,level+1);
}
int main()
{
node* T; int n;
cin >> n;
for (int i = 0; i < n; i++)
cin >> in[i];
for (int i = 0; i < n; i++)
cin >> post[i];
create(0, n - 1, 0, n - 1,0,0);
sort(v.begin(), v.end(), cmp);
for (int i = 0; i < v.size(); i++) {
if (i != 0) cout << " ";
cout << v[i]->data;
}
}