题目链接
二叉树的基本操作,就是有点麻烦
#include <algorithm>
#include <bitset>
#include <cmath>
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <deque>
#include <functional>
#include <iostream>
#include <map>
#include <queue>
#include <set>
#include <stack>
#include <string>
#include <vector>
using namespace std;
vector<int> s1;//记录非镜像前序
vector<int> s2;//记录镜像前序
int a[1010], n;
struct node {
int data;
struct node *left;
struct node *right;
};
struct node *creat(struct node *root, int x) { //非镜像建树
if (root == NULL) {
root = new node;
root->data = x;
root->left = NULL;
root->right = NULL;
} else {
if (x < root->data)
root->left = creat(root->left, x);
else
root->right = creat(root->right, x);
}
return root;
}
struct node *add(struct node *tree, int x) { //镜像建树
if (tree == NULL) {
tree = new node;
tree->data = x;
tree->left = NULL;
tree->right = NULL;
} else {
if (x >= tree->data)
tree->left = add(tree->left, x);
else
tree->right = add(tree->right, x);
}
return tree;
}
void head(struct node *root) { //非镜像前序
if (root == NULL) return;
s1.push_back(root->data);
head(root->left);
head(root->right);
return;
}
void Front(struct node *tree) { //镜像前序
if (tree == NULL) return;
s2.push_back(tree->data);
Front(tree->left);
Front(tree->right);
return;
}
bool judge() { //判断非镜像前序
for (int i = 0; i < n; i++)
if (s1[i] != a[i]) return false;
return true;
}
bool check() { //判断镜像前序
for (int i = 0; i < n; i++)
if (s2[i] != a[i]) return false;
return true;
}
bool flag = 1;
void print(struct node *root) { //后序输出
if (root == NULL) return;
print(root->left);
print(root->right);
if (flag)
printf("%d", root->data);
else
printf(" %d", root->data);
flag = 0;
return;
}
int main(int argc, char const *argv[]) {
cin >> n;
struct node *root = NULL; //非镜像
struct node *tree = NULL; //镜像
for (int i = 0; i < n; i++) {
cin >> a[i];
root = creat(root, a[i]);
tree = add(tree, a[i]);
}
head(root);
Front(tree);
if (judge()) {
printf("YES\n");
print(root);
printf("\n");
} else if (check()) {
printf("YES\n");
print(tree);
printf("\n");
} else
printf("NO\n");
return 0;
}