PAT 1043.Is It a Binary Search Tree

本文详细介绍了如何使用先序遍历建立二叉查找树,并通过比较先序和镜像先序遍历来验证树的正确性。文章深入探讨了二叉树的插入操作和不同类型的遍历方法,包括先序遍历、中序遍历和后序遍历。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

掌握二叉排序树的一些常规操作就可以了。我的思路就是:按照输入的先序遍历建立二叉查找树,然后对这棵二叉查找树进行先序遍历以及镜像先序遍历。两个之中有一个对上,输出”YES”和后序遍历或者镜像后序遍历的序列。两个都对不上就输出”NO”呗。
所以不用怕镜像,也不用管镜像。

#include <cstdio>
#include <queue>
#include <algorithm>
#include <iostream>
#include <time.h>
#include <vector>
using namespace std;

const int maxn = 1011;
vector<int> prepre;
vector<int> erperp;
vector<int> post;
vector<int> tsop;
struct node{
    int data;
    node* lchild;
    node* rchild;
};

int N;
int preorder[maxn];

node* newNode(int x)
{
    node* Node = new node;
    Node->data = x;
    Node->lchild = Node->rchild =NULL;
    return Node;
}

void insertBST(node* &root,int x)//& is very important.
{
    if(root == NULL){
         root = newNode(x);
         return;
    }

    if(x == root->data)
        insertBST(root->rchild, x);
    else if(x < root->data)
        insertBST(root->lchild, x);
    else
        insertBST(root->rchild, x);

}

node* CreatBST(int data[], int n)
{
    node* root = newNode(data[0]);
    for(int i=1;i<n;i++)
        insertBST(root, data[i]);
    return root;
}

void pre_tra(node* root)
{
    if(root==NULL)
        return;
    prepre.push_back(root->data);
    pre_tra(root->lchild);
    pre_tra(root->rchild);
}


void post_tra(node* root)
{
    if(root == NULL)
        return;
    post_tra(root->lchild);
    post_tra(root->rchild);
    post.push_back(root->data);
}

void tsop_tra(node* root)
{
    if(root == NULL)
        return;
    tsop_tra(root->rchild);
    tsop_tra(root->lchild);
    tsop.push_back(root->data);
}

void erp_tra(node* root)
{
    if(root==NULL)
        return;
    erperp.push_back(root->data);
    erp_tra(root->rchild);
    erp_tra(root->lchild);
}

int main()
{
    int i,j,k;
    scanf("%d",&N);
    for(i=0;i<N;i++)
        scanf("%d",&preorder[i]);
    node* root = new node;
    root = CreatBST(preorder, N);
    pre_tra(root);
    erp_tra(root);

    int flag = 0;
    for(i=0;i<N;i++)
        if(prepre[i] != preorder[i])
            flag = 1;
    if(flag == 0)
    {
        printf("YES\n");
        post_tra(root);
    for(i=0;i<N;i++)
    {
         if(i==0)
            printf("%d",post[i]);
        else
            printf(" %d",post[i]);
    }
    return 0;
    }

    flag = 0;
    for(i=0;i<N;i++)
        if(erperp[i] != preorder[i])
            flag = 1;
    if(flag == 0)
    {
        printf("YES\n");
        tsop_tra(root);
    for(i=0;i<N;i++)
    {
         if(i==0)
            printf("%d",tsop[i]);
        else
            printf(" %d",tsop[i]);
    }
    }
    else
    {
        printf("NO\n");
        return 0;
    }


}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值