按先序的顺序建搜索树,然后先序遍历和先序比对,如果不一样再按NRL的顺序遍历比对。
#include <iostream>
#include <vector>
#define MAX 1010
using namespace std;
int list[MAX];
int N;
struct Node {
int data;
Node * l;
Node * r;
Node() { data = -1; l = NULL; r = NULL; }
};
typedef Node * Tree;
vector <int> pre;
vector <int> preCheck;
vector <int> post;
void builTree(int num ,Tree &t) {
if (t == NULL) {
t = new Node;
t->data = num;
}
else if(num < t->data && t->data >0){
builTree(num, t->l);
}
else if (num >= t->data && t->data > 0) {
builTree(num, t->r);
}
else
return;
}
void preOreder(Tree t) {
if (t) {
preCheck.push_back(t->data);
preOreder(t->l);
preOreder(t->r);
}
}
void preOrederM(Tree t) {
if (t) {
preCheck.push_back(t->data);
preOrederM(t->r);
preOrederM(t->l);
}
}
void postOreder(Tree t) {
if (t) {
postOreder(t->l);
postOreder(t->r);
post.push_back(t->data);
}
}
void postOrederM(Tree t) {
if (t) {
postOrederM(t->r);
postOrederM(t->l);
post.push_back(t->data);
}
}
void printV() {
for (int i = 0; i < post.size() - 1; i++) {
cout << post[i] << " ";
}
cout << post[post.size() - 1] << endl;
}
int main() {
cin >> N;
Tree T = NULL;
int temp;
for (int i = 0; i < N; i++) {
cin >> temp;
builTree(temp, T);
pre.push_back(temp);
}
bool tag = true;
preOreder(T);
for (int i = 0; i < pre.size(); i++) {
if (pre[i] != preCheck[i])
tag = false;
}
if (tag) {
postOreder(T);
cout << "YES" << endl;
printV();
return 0;
}
//镜像
tag = true;
preCheck.clear();
preOrederM(T);
for (int i = 0; i < pre.size(); i++) {
if (pre[i] != preCheck[i])
tag = false;
}
if (tag) {
postOrederM(T);
cout << "YES" << endl;
printV();
return 0;
}
else {
cout << "NO" << endl;
}
system("pause");
return 0;
}