题目思路:先建树,先序遍历一遍和输入的比较判断是yes还是no,然后注意镜像树先序就是先遍历右边的 后序也先遍历右边的
#include<iostream>
#include<vector>
#include<queue>
#include<stack>
#include<string>
#include<math.h>
#include<algorithm>
using namespace std;
struct node {
int data;
node* left, * right;
};
void insert(node* &root, int data)
{
if (root == NULL)
{
root = new node;
root->data = data;
root->left = root->right = NULL;
return;
}
if (data < root->data) insert(root->left, data);
else insert(root->right, data);
}
void preorder1(node* root, vector<int>& v1)
{
if (root == NULL) return;
v1.push_back(root->data);
preorder1(root->left, v1);
preorder1(root->right, v1);
}
void preorder2(node* root, vector<int>& v1)
{
if (root == NULL) return;
v1.push_back(root->data);
preorder2(root->right, v1);
preorder2(root->left, v1);
}
void postorder1(node* root, vector<int>& v1)
{
if (root == NULL) return;
postorder1(root->left, v1);
postorder1(root->right, v1);
v1.push_back(root->data);
}
void postorder2(node* root, vector<int>& v1)
{
if (root == NULL) return;
postorder2(root->right, v1);
postorder2(root->left, v1);
v1.push_back(root->data);
}
vector<int>v0,v1, v2, v3, v4;
int main()
{
int n, data;
cin >> n;
node* root = NULL;
for (int i = 0; i < n; i++)
{
cin >> data;
v0.push_back(data);
insert(root, data);
}
preorder1(root, v1);
preorder2(root, v2);
postorder1(root, v3);
postorder2(root, v4);
if (v0 == v1)
{
cout << "YES" << endl;
for (int i = 0; i < v3.size(); i++)
{
cout << v3[i];
if (i < v3.size() - 1)
cout << " ";
}
}
else if (v0 == v2)
{
cout << "YES" << endl;
for (int i = 0; i < v4.size(); i++)
{
cout << v4[i];
if (i < v4.size() - 1)
cout << " ";
}
}
else
{
cout << "NO" << endl;
}
}