[GPLT]L2-004. 这是二叉搜索树吗?

题目链接

https://www.patest.cn/contests/gplt/L2-004


题意

一棵二叉搜索树可被递归地定义为具有下列性质的二叉树:对于任一结点,

其左子树中所有结点的键值小于该结点的键值;
其右子树中所有结点的键值大于等于该结点的键值;
其左右子树都是二叉搜索树。
所谓二叉搜索树的“镜像”,即将所有结点的左右子树对换位置后所得到的树。

给定一个整数键值序列,现请你编写程序,判断这是否是对一棵二叉搜索树或其镜像进行前序遍历的结果。


题解

区间递归
对于起始区间,前序遍历的第一个数的根结点,[root+1,tail]就是root结点的所有结点
对于[root+1,tail]结点因为是二叉搜索树必须满足[root+1,i] < root, [i+1,tail] >= root;
对于镜像二叉搜索树则相反 [root+1,i] >= root [i+1,tail] < root;

如果不满足则返回false;
如果当前满足将 [root+1,tail] 分成 [root+1,i] 和 [i+1,tail] 分别是root的左子树和右子树.
在将这两个区间进行递归。

arr 数组存放的就是后序遍历. - arr 在子树递归完才添加


代码

#include<iostream>
#include<cstdio>
#include<cstring>
#include<algorithm>
#include<vector>
using namespace std;
const int maxn = 1010;
int nodes[maxn];
vector<int> arr;
int n;
bool Tree(int root,int tail)    ///确定一个范围根结点所管辖的范围为[root+1,tail]
{
    if(root > tail) return true;
    int i = root + 1,j = tail;
    while(i <= tail && nodes[i] < nodes[root]) i++;
    while(j > root && nodes[j] >= nodes[root]) j--;
    if(i!=j+1) return false;
    if(!Tree(root+1,j)) return false;
    if(!Tree(i,tail)) return false;
    arr.push_back(root);
    return true;
}
bool TreeMirror(int root,int tail)
{
    if(root > tail) return true;
    int i = root + 1,j = tail;
    while(i <= tail && nodes[i] >= nodes[root]) i++;
    while(j > root && nodes[j] < nodes[root]) j--;
    if(i!=j+1) return false;
    if(!TreeMirror(root+1,j)) return false;
    if(!TreeMirror(i,tail)) return false;
    arr.push_back(root);
    return true;
}
void print()
{
    int len = arr.size();
    printf("YES\n");
    for(int i=0;i<len-1;i++) printf("%d ",nodes[arr[i]]);printf("%d\n",nodes[arr[len-1]]);
}
int main()
{
    while(~scanf("%d",&n))
    {
        for(int i=1;i<=n;i++) scanf("%d",&nodes[i]);
        arr.clear();
        if(Tree(1,n)) print();
        else {
            arr.clear();
            if(TreeMirror(1,n)) print();
            else printf("NO\n");
        }
    }
    return 0;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值