PAT ~ L2-004. 这是二叉搜索树吗?(树的遍历,二叉搜索树性质)

思路:太菜了,看参考别人博客才会的。我们先假设他给的这个序列就是该二叉搜索树的先序遍历,我们去进行遍历这个二叉搜索树,并处理出来它的后序遍历结果。如果遍历过程中,发现某个子树不是正好分为左右两部分(左边的值都小与根,右边的值都大于根)直接return。最后回溯过程中依次把根存入vector数组就是后序遍历结果。

如果不符合前序遍历的话,因为中间有直接return的时候,所以存入vector数组中的数字个数肯定少于N。

同样的方法再判断一下“镜像”就可以了。

#include<bits/stdc++.h>
using namespace std;
const int MAXN = 1e3 + 5;
int n;
vector<int> a, ans;
void check1(int root, int End)
{
    if (root > End) return ;
    int i = root + 1, j = End;
    while (i <= End && a[i] <  a[root]) i++;
    while (j > root && a[j] >= a[root]) j--;
    if (i - 1 != j) return ;
    check1(root + 1, i - 1);
    check1(j + 1, End);
    ans.push_back(a[root]);
}
void check2(int root, int End)
{
    if (root > End) return ;
    int i = root + 1, j = End;
    while (i <= End && a[i] >= a[root]) i++;
    while (j > root && a[j] <  a[root]) j--;
    if (i - 1 != j) return ;
    check2(root + 1, i - 1);
    check2(j + 1, End);
    ans.push_back(a[root]);
}
int main()
{
    while (~scanf("%d", &n))
    {
        a.clear(); ans.clear();
        for (int i = 0; i < n; i++)
        {
            int x; scanf("%d", &x);
            a.push_back(x);
        }
        check1(0, n - 1);
        if (ans.size() != n)
        {
            ans.clear();
            check2(0, n - 1);
        }
        if (ans.size() == n)
        {
            printf("YES\n");
            for (int i = 0; i < n; i++)
            {
                printf("%d", ans[i]);
                if (i != n - 1) printf(" ");
                else printf("\n");
            }
        }
        else printf("NO\n");
    }
    return 0;
}
/*
7
8 6 5 7 10 8 11
7
8 10 11 8 6 7 5
7
8 6 8 5 10 9 11
*/


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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值