搜索树判断

对于二叉搜索树,我们规定任一结点的左子树仅包含严格小于该结点的键值,而其右子树包含大于或等于该结点的键值。如果我们交换每个节点的左子树和右子树,得到的树叫做镜像二叉搜索树。

现在我们给出一个整数键值序列,请编写程序判断该序列是否为某棵二叉搜索树或某镜像二叉搜索树的前序遍历序列,如果是,则输出对应二叉树的后序遍历序列。

输入格式:

输入的第一行包含一个正整数N(≤1000),第二行包含N个整数,为给出的整数键值序列,数字间以空格分隔。

输出格式:

输出的第一行首先给出判断结果,如果输入的序列是某棵二叉搜索树或某镜像二叉搜索树的前序遍历序列,则输出YES,否侧输出NO。如果判断结果是YES,下一行输出对应二叉树的后序遍历序列。数字间以空格分隔,但行尾不能有多余的空格。

输入样例1:

7
8 6 5 7 10 8 11

输出样例1:

YES
5 7 6 8 11 10 8

输入样例2:

7
8 6 8 5 10 9 11

输出样例2:

NO

  1 #include <bits/stdc++.h>
  2 using namespace std;
  3 
  4 typedef struct BNode* BTree;
  5 struct BNode
  6 {
  7     int date;
  8     BTree left;
  9     BTree right;
 10 };
 11 int a[1005],b[1005],c[1005];
 12 int cnt=0,cnt2=0,flag=1;
 13 
 14 void Insert(BTree &t,int date)
 15 {
 16     if(!t)
 17     {
 18         BTree p=(BTree)malloc(sizeof(BTree));
 19         p->date=date;
 20         p->left=NULL;
 21         p->right=NULL;
 22         t=p;
 23     }
 24     else if(date<t->date)Insert(t->left,date);
 25     else if(date>=t->date)Insert(t->right,date);
 26 }
 27 
 28 void BDLR(BTree t)
 29 {
 30     if(t)
 31     {
 32         b[cnt++]=t->date;
 33         BDLR(t->left);
 34         BDLR(t->right);
 35     }
 36 }
 37 
 38 void BJDLR(BTree t)
 39 {
 40     if(t)
 41     {
 42         c[cnt2++]=t->date;
 43         BJDLR(t->right);
 44         BJDLR(t->left);
 45     }
 46 }
 47 
 48 void LRD(BTree t)
 49 {
 50     if(t)
 51     {
 52         LRD(t->left);
 53         LRD(t->right);
 54         if(flag)
 55         flag=0;
 56         else
 57         cout<<" ";
 58         cout<<t->date; 
 59     }
 60 }
 61 
 62 void JLRD(BTree t)
 63 {
 64     if(t)
 65     {
 66         JLRD(t->right);
 67         JLRD(t->left);
 68         if(flag)
 69         flag=0;
 70         else
 71         cout<<" ";
 72         cout<<t->date; 
 73     }
 74 }
 75 
 76 int main()
 77 {
 78     int n;
 79     cin>>n;
 80     BTree t;
 81     t=NULL;
 82     for(int i=0;i<n;i++){
 83     cin>>a[i];
 84     Insert(t,a[i]);
 85     }
 86     BDLR(t);
 87     BJDLR(t);
 88     int f=0,p=0;
 89     for(int i=0;i<n;i++)
 90     {
 91         if(a[i]!=b[i])
 92         {
 93             f=1;
 94             break;
 95         }
 96     }
 97     for(int i=0;i<n;i++)
 98     {
 99         if(a[i]!=c[i])
100         {
101             p=1;
102             break;
103         }
104     }
105     if(f&&p)cout<<"NO"<<endl;
106     else if(!f)
107     {
108         cout<<"YES"<<endl;
109         LRD(t);
110     }
111     else if(!p)
112     {
113         cout<<"YES"<<endl;
114         JLRD(t);
115     }
116 }

 

posted on 2019-02-25 13:49  Esther6  阅读(339)  评论(0)    收藏  举报

导航