PAT甲级真题1043 判断二叉搜索树

二叉搜索树 (BST) 递归定义为具有以下属性的二叉树:

若它的左子树不空,则左子树上所有结点的值均小于它的根结点的值
若它的右子树不空,则右子树上所有结点的值均大于或等于它的根结点的值
它的左、右子树也分别为二叉搜索树
我们将二叉搜索树镜面翻转得到的树称为二叉搜索树的镜像。

现在,给定一个整数序列,请你判断它是否可能是某个二叉搜索树或其镜像进行前序遍历的结果。

二叉树的镜像在这

在这里插入图片描述

输入格式
第一行包含整数 N,表示节点数量。

第二行包含 N 个整数。

输出格式
如果给定整数序列是某个二叉搜索树或其镜像的前序遍历序列,则在第一行输出 YES,否则输出 NO。

如果你的答案是 YES,则还需要在第二行输出这棵树的后序遍历序列。

数据范围
1≤N≤1000
输入样例17
8 6 5 7 10 8 11
输出样例1:
YES
5 7 6 8 11 10 8
输入样例27
8 10 11 8 6 7 5
输出样例2:
YES
11 8 10 7 5 6 8
输入样例37
8 6 8 5 10 9 11
输出样例3:
NO
#include <cstring>
#include <iostream>
#include <algorithm>

using namespace std;

const int N = 1010;

int n;
int preorder[N], inorder[N];
int postorder[N], cnt;
//返回值是否创建成功 
bool build(int il, int ir, int pl, int pr, int type)//把这个子树的根节点加进去 
{
    if (il > ir) return true;//这个创造好了,下面没结点了,肯定创造成功 

    int root = preorder[pl];
    int k;//设置在外面
    if (type == 0)
    {
        for (k = il; k <= ir; k ++ )
            if (inorder[k] == root)
                break;  //先找到根 
        if (k > ir) return false;
    }
    else
    {
        for (k = ir; k >= il; k -- ) //从右到左遍历
            if (inorder[k] == root)
                break;
        if (k < il) return false;
    }

    bool res = true;
    if (!build(il, k - 1, pl + 1, pl + 1 + (k - 1 - il), type)) res = false;//先递归遍历左子树 
    if (!build(k + 1, ir, pl + 1 + (k - 1 - il) + 1, pr, type)) res = false;//在递归遍历右子树 

    postorder[cnt ++ ] = root;
    return res;
}

int main()
{
    cin >> n;
    for (int i = 0; i < n; i ++ )
    {
        cin >> preorder[i];
        inorder[i] = preorder[i];
    }

    sort(inorder, inorder + n);

    if (build(0, n - 1, 0, n - 1, 0))
    {
        puts("YES");
        cout << postorder[0];
        for (int i = 1; i < n; i ++ ) cout << ' ' << postorder[i];
        cout << endl;
    }
    else //判断是否为镜像,镜像是相反的存 
    {
        reverse(inorder, inorder + n);
        cnt = 0;//再重新从小到大存 
        if (build(0, n - 1, 0, n - 1, 1))
        {
            puts("YES");
            cout << postorder[0];
            for (int i = 1; i < n; i ++ ) cout << ' ' << postorder[i];
            cout << endl;
        }
        else puts("NO");
    }
    return 0;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

小王子y

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值