L2-004 这是二叉搜索树吗?

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

  • 其左子树中所有结点的键值小于该结点的键值;
  • 其右子树中所有结点的键值大于等于该结点的键值;
  • 其左右子树都是二叉搜索树。

所谓二叉搜索树的“镜像”,即将所有结点的左右子树对换位置后所得到的树。

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

输入格式:

输入的第一行给出正整数 N(≤1000)。随后一行给出 N 个整数键值,其间以空格分隔。

输出格式:

如果输入序列是对一棵二叉搜索树或其镜像进行前序遍历的结果,则首先在一行中输出 YES ,然后在下一行输出该树后序遍历的结果。数字间有 1 个空格,一行的首尾不得有多余空格。若答案是否,则输出 NO

输入样例 1:

7
8 6 5 7 10 8 11

输出样例 1:

YES
5 7 6 8 11 10 8

输入样例 2:

7
8 10 11 8 6 7 5

输出样例 2:

YES
11 8 10 7 5 6 8

输入样例 3:

7
8 6 8 5 10 9 11

输出样例 3:

NO

参考:https://blog.csdn.net/liuchuo/article/details/52160484

思路:

我们不确定一个树是不是二叉搜索树,假定它是,然后判断:

若第一个元素为根,则从左向右方向是根的左子树都小于根,从右向左是右子数,都大于根,设两个指针遍历,若两个指针恰好遍历完所有元素,则该元素成立,递归判断其左右子树,最后把该元素放入数组,这正好满足后序遍历。

判断数组里元素的个数是否是n,若不是,说明不是二叉搜索树

则判断是不是镜像。

代码如下:

#include<iostream>
#include<cstdio>
#include<algorithm>
#include<string>
#include<cstring>
#include<queue>
#include<stack>
#include<cmath>
#include<set>
#include<map>
using namespace std;
#define ll long long
#define lson l,m,rt<<1
#define rson m+1,r,rt<<1|1
typedef pair<int,int>P;
const int INF=0x3f3f3f3f;
const int N=1015,mod=32767;
bool isMirror=false;
vector<int>pre;
vector<int>post;
void getpost(int root,int tail){
    if(root>tail)return ;
    int i=root+1,j=tail;
    if(!isMirror){
        while(i<=tail&&pre[root]>pre[i])i++;
        while(j>root&&pre[root]<=pre[j])j--;
    }
    else{
        while(i<=tail&&pre[root]<=pre[i])i++;
        while(j>root&&pre[root]>pre[j])j--;
    }
    if(i-j!=1)return ;
    getpost(root+1,j);
    getpost(i,tail);
    post.push_back(pre[root]);
}
int main(){
    int n;
    scanf("%d",&n);
    pre.resize(n);
    for(int i=0;i<n;i++)scanf("%d",&pre[i]);
    getpost(0,n-1);
    if(post.size()!=n){
        isMirror=true;
        post.clear();
        getpost(0,n-1);
    }
    if(post.size()==n){
        printf("YES\n%d",post[0]);
        for(int i=1;i<n;i++){
            printf(" %d",post[i]);
        }
        printf("\n");
    }
    else printf("NO\n");
}

猜你喜欢

转载自blog.csdn.net/m0_37579232/article/details/87906025