【資料結構】進擊的二叉查詢樹
阿新 • • 發佈:2018-12-21
Description
給定1~N的兩個排列,使用這兩個排列分別構建兩棵二叉查詢樹(也就是通過往一棵空樹中依次插入序列元素的構建方式)。如果這兩棵二叉查詢樹完全相同,那麼輸出YES;否則輸出NO。之後,輸出第一個排列對應的二叉查詢樹的後序序列、層序序列。
Input
每個輸入檔案中一組資料。
第一行1個正整數N(1<=N<=30),表示二叉查詢樹中的結點個數。
接下來兩行,代表1~N的兩個排列。
Output
如果兩個排列代表的二叉查詢樹完全相同,那麼輸出一行YES,否則輸出一行NO。
接下來兩行分別輸出第一個排列對應的二叉查詢樹的後序序列、層序序列,整數之間用空格隔開。
每行末尾不允許有多餘的空格。
Sample Input
5 4 2 1 3 5 4 5 2 3 1
Sample Output
YES 1 3 2 5 4 4 2 5 1 3
/************************************************************** Problem: 2943 User: 201717010009 Language: C++ Result: Accepted Time:0 ms Memory:1720 kb ****************************************************************/ #include<iostream> #include<algorithm> #include<cstdio> #include<malloc.h> #include<bits/stdc++.h> using namespace std; int n,num,a[100],b[100],i; int Q1[100],Z1[100],Q2[100],Z2[100]; typedef struct BSTNode{ int data; struct BSTNode *lchild; struct BSTNode *rchild; }BSTNode,*PBSTNode; PBSTNode insert(int data,PBSTNode *root){ if(*root == NULL) { *root=(PBSTNode)malloc(sizeof(BSTNode)); (*root)->data=data; (*root)->lchild=NULL; (*root)->rchild=NULL; return *root; } if(data<(*root)->data) (*root)->lchild=insert(data,&( (*root)->lchild) ); else if(data>(*root)->data) (*root)->rchild=insert(data,&( (*root)->rchild) ); return *root; } void QX1(PBSTNode root){//得到第一序列的前序序列 if(root!=NULL) { Q1[i++]=root->data; QX1(root->lchild); QX1(root->rchild); } } void ZX1(PBSTNode root){//得到第一序列的中序序列 if(root!=NULL) { ZX1(root->lchild); Z1[i++]=root->data; ZX1(root->rchild); } } void QX2(PBSTNode root){//得到第二序列的前序序列 if(root!=NULL) { Q2[i++]=root->data; QX2(root->lchild); QX2(root->rchild); } } void ZX2(PBSTNode root){//得到第二序列的中序順序 if(root!=NULL) { ZX2(root->lchild); Z2[i++]=root->data; ZX2(root->rchild); } } void HX(PBSTNode root){ if(root!=NULL) { HX(root->lchild); HX(root->rchild); printf("%d",root->data); if(num<n-1){ cout<<" ";num++; } } } void CX(PBSTNode root){ PBSTNode q[100]; int w=1,t=1;//建隊 if(root==NULL){ return ; } q[w++]=root; while(t!=w){ if(q[t]->lchild!=NULL){ q[w++]=q[t]->lchild; } if(q[t]->rchild!=NULL){ q[w++]=q[t]->rchild; } cout<<q[t]->data; if(num<n-1){ cout<<" ";num++; } t++; } } int main(){ PBSTNode root1=NULL,root2=NULL; cin>>n; for(i=0;i<n;i++){ cin>>a[i]; insert(a[i],&root1); } for(i=0;i<n;i++){ cin>>b[i]; insert(b[i],&root2); } i=0;QX1(root1); i=0;ZX1(root1); i=0;QX2(root2); i=0;ZX2(root2); int flag=0; for(i=0;i<n;i++){//比較前序序列 if(Q1[i]!=Q2[i]){ cout<<"NO"<<endl; flag=1;break; } } for(i=0;i<n;i++){//比較後序序列 if(flag==1)break; if(Z1[i]!=Z2[i]){ cout<<"NO"<<endl; flag=1;break; } } if(!flag){ cout<<"YES"<<endl; } num=0; HX(root1); cout<<endl; num=0; CX(root1); }