PAT甲级-1043 Is It a Binary Search Tree (25分)

题目:1043 Is It a Binary Search Tree (25分)
分析:二叉搜索树的判断(BST),本题要求判断输入序列是不是二叉搜索树的前序或者是该二叉搜索树的镜像的前序,代码有点长,但易懂
#include <iostream>
#include<cstring>
#include<vector>
#include<stdio.h>
#include<queue>
#include<math.h>
#include<stack>
#include<algorithm>
#include<map>
#include<set>
#define MAX 99999999
typedef long long ll;
using namespace std;
int n,m;
vector<int>pre;
struct node{

    int data;
    struct node* left;
    struct node* right;
};
int f;
void posTraversal1(node*root)
{
    if(root == NULL)return ;
    posTraversal1(root->left);
    posTraversal1(root->right);
    if(f == 0){
        cout<<root->data;
        f = 1;
    }

    else
        cout<<" "<<root->data;
}
void posTraversal2(node*root)
{
    if(root == NULL)return ;
    posTraversal2(root->right);
    posTraversal2(root->left);
    if(f == 0){
        cout<<root->data;
        f = 1;
    }

    else
        cout<<" "<<root->data;
}
void inser(node *&root,int x)
{
    if(root == NULL)
    {
        root = (node*)malloc(sizeof(node));
        root->data = x;
        root->left = NULL;
        root->right = NULL;
    }
    else if(root->data <= x)
        inser(root->right,x);
    else inser(root->left,x);
}
node* create()
{
    node* root = NULL;
    for(int i = 0;i<n;i++)
        inser(root,pre[i]);
    return root;
}
vector<int>test_pre1;
void judge1(node *root)
{
    if(root == NULL)
        return ;
    test_pre1.push_back(root->data);
    judge1(root->left);
    judge1(root->right);
}
void judge2(node *root)
{
    if(root == NULL)
        return ;
    test_pre1.push_back(root->data);
    judge2(root->right);
    judge2(root->left);
}
int main()
{
    cin>>n;
    for(int i = 0;i<n;i++){
        int x;
        cin>>x;
        pre.push_back(x);
    }
    node*root = create();//根据输入建立BST
    judge1(root);//判断树是不是
    if(test_pre1 == pre)
    {
        cout<<"YES\n";
        posTraversal1(root);
    }
    else{
        test_pre1.clear();
        judge2(root);//判断镜像的树
        if(test_pre1 == pre)
        {
            cout<<"YES\n";
            posTraversal2(root);
        }
        else
            cout<<"NO";
    }
    return 0;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值