1043. Is It a Binary Search Tree

 

http://www.patest.cn/contests/pat-a-practise/1043




  1 #include <stdio.h>
  2 #include <vector>
  3 using namespace std;
  4  
  5 struct Node
  6 {
  7    Node* lchild;
  8    Node* rchild;
  9    int val;
 10 }Tree[2000];
 11  
 12 int loc,loc2,loc3;
 13 Node* create()
 14 {
 15 Tree[loc].lchild=NULL;
 16 Tree[loc].rchild=NULL;
 17 return &Tree[loc++];
 18 }
 19  
 20 Node* insert1(Node* T,int v)//二叉排序树构建
 21 {
 22       if(T==NULL)
 23  {
 24  T=create();
 25  T->val=v;
 26  }
 27  else
 28  {
 29  if(v<T->val)  T->lchild=insert1(T->lchild,v);
 30  else T->rchild=insert1(T->rchild,v);
 31  }
 32  return T;
 33 }
 34  
 35 Node* insert2(Node* T,int v)//镜像二叉排序树构建
 36 {
 37    if(T==NULL)
 38    {
 39   T=create();
 40   T->val=v;
 41    }
 42    else
 43    {
 44   if(v>=T->val)  T->lchild=insert2(T->lchild,v);
 45   else  T->rchild=insert2(T->rchild,v);
 46    }
 47  
 48    return T;
 49 }
 50  
 51  
 52  
 53 void preorder(Node *T,int ans[])
 54 {
 55  
 56      if(T!=NULL)
 57 {
 58 ans[loc2++]=T->val;
 59 if(T->lchild!=NULL) preorder(T->lchild,ans);
 60 if(T->rchild!=NULL) preorder(T->rchild,ans);
 61 }
 62 }
 63  
 64 void postorder(Node* T,int ans[])
 65 {
 66    if(T!=NULL)
 67    {
 68   if(T->lchild!=NULL) postorder(T->lchild,ans);
 69   if(T->rchild!=NULL) postorder(T->rchild,ans);
 70   ans[loc3++]=T->val;
 71    }
 72 }
 73  
 74  
 75 bool compare(int a[],int b[],int n)//比较序列 
 76 {
 77 bool bo=true;
 78 for(int i=0;i<n;i++)
 79 {
 80    if(a[i]!=b[i])
 81 {
 82 bo=false;break;
 83 }
 84 }
 85  
 86 return bo;
 87 }
 88  
 89  
 90  
 91 int main()
 92 {
 93 int n,i;
 94 //二叉排序树的前序就是构建树的插入顺序
 95 //所以只要按照前序建立二叉排序树 和 镜像二叉排序树,得出两者的前序
 96 //与输入的序列比较,如果其中之一相等,则YES,并输出该树的中序。否则,NO。
 97 while(scanf("%d",&n)!=EOF)
 98 {
 99 getchar();
100     int v1[1000];//存储 输入序列
101     int pre1[1000];//存储  二叉排序树的前序
102     int pre2[1000];//存储  镜像二叉排序树的前序
103     int post[1000];//存储 后序遍历
104 loc=0; loc3=0;
105 Node *T1=NULL,*T2=NULL;
106 for(i=0;i<n;i++)//建树
107 {
108 scanf("%d",&v1[i]);
109 T1=insert1(T1,v1[i]);
110 T2=insert2(T2,v1[i]);
111 }
112     getchar();
113 loc2=0;
114 preorder(T1,pre1);
115 loc2=0;
116 preorder(T2,pre2);
117 bool b1=compare(v1,pre1,n),b2=compare(v1,pre2,n);
118  
119 if(!b1&&!b2)
120 {
121    printf("NO\n");
122    }
123 else
124 {
125 printf("YES\n");
126 if(b1)  postorder(T1,post);
127 else  postorder(T2,post);
128  
129 for(i=0;i<n;i++)
130     printf("%d%c",post[i],i==n-1?'\n':' ');
131 } 
132 }
133    return 0;
134 }

 

posted @ 2015-01-28 13:41  小爷  阅读(226)  评论(0编辑  收藏  举报