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

来源:互联网 发布:2016零售业数据 编辑:程序博客网 时间:2024/06/05 06:18

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

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

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

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

输入格式:

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

输出格式:

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

输入样例1:
78 6 5 7 10 8 11
输出样例1:
YES5 7 6 8 11 10 8
输入样例2:
78 10 11 8 6 7 5
输出样例2:
YES11 8 10 7 5 6 8
输入样例3:
78 6 8 5 10 9 11
输出样例3:
NO
#include <iostream>#include <cstring>#include <cstdio>using namespace std;struct BST{    int data;    BST *lchild;    BST *rchild;    BST(int a){data = a; lchild = rchild = NULL;}    //构造函数};int _size = 0;bool judge3 = 0;BST* build(BST *root, int a){    if(!root)        root = new BST(a);    else if(root->data > a)        root->lchild = build(root->lchild, a);         //!!! root->lchild =,    else        root->rchild = build(root->rchild, a);    return root;}void PreOrder(BST *root, int *p){    if(!root)        return ;    p[_size++] = root->data;    PreOrder(root->lchild, p);    PreOrder(root->rchild, p);}void MirPreOrder(BST *root, int  *p){    if(!root)        return ;    p[_size++] = root->data;    MirPreOrder(root->rchild, p);    MirPreOrder(root->lchild, p);}void PostOrder(BST *root){    if(!root)        return;    PostOrder(root->lchild);    PostOrder(root->rchild);    if(judge3 == 0)    {        printf("%d",root->data);        judge3 = 1;    }    else        printf(" %d",root->data);}void MirPostOrder(BST *root){    if(!root)        return;    MirPostOrder(root->rchild);    MirPostOrder(root->lchild);    if(judge3 == 0)    {        printf("%d",root->data);        judge3 = 1;    }    else        printf(" %d",root->data);}int main(){    int a[1000 + 5];    int  n;    BST *root;    root = NULL;                    // !!!BST*root; root=NULL!!!!    cin>>n;    for(int i = 0; i < n; i++)    {        scanf("%d",&a[i]);        root = build(root,a[i]);    }    int num[1000+5];    bool judge1 = 1, judge2 = 1;    PreOrder(root,num);    for(int i = 0; i < n; i++)        if(num[i] != a[i])        {            judge1 = 0;            break;        }    _size = 0;    MirPreOrder(root,num);    for(int i = 0; i < n; i++)    {        if(num[i] != a[i])        {            judge2 = 0;            break;        }    }    if(judge2 || judge1)    {        if(judge1)        {            cout<<"YES"<<endl;            PostOrder(root);            cout<<endl;        }        else        {            cout<<"YES"<<endl;            MirPostOrder(root);            cout<<endl;        }    }    else        cout<<"NO"<<endl;
}






0 0