//
// 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题解
最新推荐文章于 2022-03-17 20:06:18 发布
这是一篇关于PAT(Panda Algorithm Test) A1043题目的解题报告。文章详细介绍了如何用C++实现二叉树的前序、中序、后序遍历,并通过遍历结果判断二叉树是否为有序数组。代码中包含了二叉树节点的定义、插入函数以及四种遍历方式的实现。
338

被折叠的 条评论
为什么被折叠?



