PATA1043题解

这是一篇关于PAT(Panda Algorithm Test) A1043题目的解题报告。文章详细介绍了如何用C++实现二叉树的前序、中序、后序遍历,并通过遍历结果判断二叉树是否为有序数组。代码中包含了二叉树节点的定义、插入函数以及四种遍历方式的实现。
摘要由CSDN通过智能技术生成
//
//  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;
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值