//
// main.cpp
// PATA1043
//
// Created by Phoenix on 2018/2/11.
// Copyright © 2018年 Phoenix. All rights reserved.
//
#include <iostream>
#include <cstdio>
const int maxn = 1010;
int n;
int pre[maxn], mirror[maxn];
struct node {
int data;
node *lchild, *rchild;
};
node* newNode(int x) {
node* root = new node;
root->data = x;
root->lchild = root->rchild = NULL;
return root;
}
void insert(node* &root, int x) {
if(root == NULL) {
root = newNode(x);
return;
}
if(root->data > x) {
insert(root->lchild, x);
}else {
insert(root->rchild, x);
}
}
node* create(int data[], int n) {
node* root = NULL;
for(int i = 0; i < n; i++) {
insert(root, data[i]);
}
return root;
}
int preNum = 0;
void preorder(node* root) {
if(root == NULL) return;
pre[preNum++] = root->data;
preorder(root->lchild);
preorder(root->rchild);
}
int mirNum = 0;
void mirorder(node* root) {
if(root == NULL) return;
mirror[mirNum++] = root->data;
mirorder(root->rchild);
mirorder(root->lchild);
}
int num = 0;
void postorder(node* root) {
if(root == NULL) return;
postorder(root->lchild);
postorder(root->rchild);
printf("%d", root->data);
if(num < n - 1) {
printf(" ");
num++;
}
}
void postmirorder(node* root) {
if(root == NULL) return;
postmirorder(root->rchild);
postmirorder(root->lchild);
printf("%d", root->data);
if(num < n - 1) {
printf(" ");
num++;
}
}
int main(int argc, const char * argv[]) {
scanf("%d", &n);
int data[n];
for(int i = 0; i < n; i++) {
scanf("%d", &data[i]);
}
node* root = create(data, n);
bool flag1 = true, flag2 = true;
preorder(root);
mirorder(root);
for(int i = 0; i < n; i++) {
if(pre[i] != data[i]) flag1 = false;
if(mirror[i] != data[i]) flag2 = false;
}
if(flag1 == false && flag2 == false){
printf("NO\n");
}
if(flag1 == true){
printf("YES\n");
postorder(root);
}else if(flag2 == true) {
printf("YES\n");
postmirorder(root);
}
return 0;
}
PATA1043题解
最新推荐文章于 2020-02-22 23:52:47 发布
![](https://img-home.csdnimg.cn/images/20240711042549.png)