PAT A1043

clipboard.png
简单的不用考虑平衡的二叉查询树;
我发现我有读题障碍症。。。

#include<iostream>
#include<stdlib.h>
#include<stdio.h>
#include<vector>
using namespace std;
using std::vector;
int n;
struct node{
    int data;
    node* lchild;
    node* rchild;
};
vector<int>input;
vector<int>inorder_;
vector<int>change_inorder_;
vector<int>postorder_;
vector<int>change_postorder_;
node* newNode(int x){
    node* root=new node;
    root->lchild=NULL;
    root->data=x;
    root->rchild=NULL;
    return root;
}

void insert(node* &root,int x){
    if(root==NULL){
        root=newNode(x);
        return ;
    }
    if(x<root->data){
        insert(root->lchild,x);
    }else{
        insert(root->rchild,x);
    }
    return ;
}

void inorder(node* root,vector<int>& vi){
    if(root==NULL)
        return;
    vi.push_back(root->data);
    inorder(root->lchild,vi);
    inorder(root->rchild,vi);
}

void postorder_change(node* root){
    if(root==NULL)
        return;
    postorder_change(root->lchild);
    postorder_change(root->rchild);
    swap(root->lchild,root->rchild);
}

void postorder(node* root,vector<int>& vi){
    if(root==NULL)
        return;
    postorder(root->lchild,vi);
    postorder(root->rchild,vi);
    vi.push_back(root->data);
}

int main(){
    int mem;
    node* root=NULL;
    scanf("%d",&n);
    for(int i=0;i<n;i++){
        scanf("%d",&mem);
        insert(root,mem);
        input.push_back(mem);
    }
    inorder(root,inorder_);
    postorder(root,postorder_);
    postorder_change(root);
    inorder(root,change_inorder_);
    postorder(root,change_postorder_);
    if(inorder_==input){
        printf("YES\n");
        for(int i=0;i<postorder_.size();i++){
            if(i==0){
                printf("%d",postorder_[i]);
            }else{
                printf(" %d",postorder_[i]);
            }
        }
    }else if(input==change_inorder_){
        printf("YES\n");
        for(int i=0;i<change_postorder_.size();i++){
            if(i==0){
                printf("%d",change_postorder_[i]);
            }else{
                printf(" %d",change_postorder_[i]);
            }
        }
    }else{
        printf("NO\n");
    }
    system("pause");
    return 0;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值