这题考试的时候真的整麻了,不知道怎么判断对错,后来查了一下资料才焕然大悟,还是太菜了,记录一下,就当是补充知识了
#include<iostream>
#include<vector>
#include<algorithm>
using namespace std;
#define N 110
int n, m;
int post[N], in[N];
vector<int>ans1, ans2;
int leftnum, rightnum = 0;
struct node
{
int data;
node* lchild;
node* rchild;
};
bool arrvie_bottom_left = false;
bool arrvie_bottom_right = false;
node* Create(int postL, int postR, int inL, int inR)
{
if (postL > postR)return nullptr;
node* root = new node;
root->data = post[postR];
int k;
for (k = inL; k < inR; k++)
{
if (in[k] == post[postR])break;
}
int numLeft = k - inL;
root->lchild = Create(postL, postL + numLeft - 1, inL, k - 1);
root->rchild = Create(postL + numLeft, postR - 1, k + 1, inR);
return root;
}
void PreOrder(node* root)
{
if (root == NULL)
{
arrvie_bottom_left = true;
leftnum = ans1[ans1.size() - 1];
return;
}
if (!arrvie_bottom_left)
{
cout << root->data << " ";
ans1.push_back(root->data);
PreOrder(root->lchild);
PreOrder(root->rchild);
}
}
void dfs(node* root)
{
if (root->lchild == NULL && root->rchild == NULL && root->data != leftnum && root->data != rightnum)
{
ans1.push_back(root->data);
cout << root->data << " ";
}
if (root->lchild != NULL)
{
dfs(root->lchild);
}
if (root->rchild != NULL)
{
dfs(root->rchild);
}
}
void PostOrder(node* root)
{
if (root == NULL)
{
arrvie_bottom_right = true;
return;
}
if (!arrvie_bottom_right)
{
//cout << root->data << " ";
ans2.push_back(root->data);
PostOrder(root->rchild);
PostOrder(root->lchild);
}
}
/*
27
5 4 6 22 3 23 7 20 2 21 8 18 9 1 10 19 11 24 17 25 12 26 16 27 13 15 14
5 6 22 4 7 23 20 3 8 21 9 18 2 10 11 24 19 12 26 25 13 27 14 15 16 17 1
11
4 8 10 2 5 1 6 3 9 11 7
10 8 4 5 2 6 11 9 7 3 1
*/
bool is_Mirror(node*root1,node*root2)
{
if (root1==NULL&&root2==NULL)return true;
if (root1 == NULL || root2 == NULL)return false;
return is_Mirror(root1->lchild,root2->rchild)&&is_Mirror(root1->rchild,root2->lchild);
}
bool is_symmetry(node*root)
{
if (root==NULL)return true;
else is_Mirror(root,root);
}
int main()
{
cin >> n;
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);
//cout << "Yes" << endl;
if(is_symmetry(root))cout << "Yes" << endl;
else cout << "No" << endl;
PreOrder(root);
dfs(root);
PostOrder(root);
ans2.erase(ans2.begin());
reverse(ans2.begin(), ans2.end());
cout << ans2[1];
for (int i = 2; i < ans2.size(); i++)
{
cout << " " << ans2[i];
}
return 0;
}