Title Description
Judging whether two sequences are the same binary search tree sequence
Input Description:
Beginning with a number n, (1 <= n <= 20) means there are n judgements to be made, and the input ends when n= 0.
The next line is a sequence with a length less than 10 and contains (0-9) numbers without duplicate numbers. Based on this sequence, a binary search tree can be constructed.
The next n rows have n sequences. Each sequence format is the same as the first sequence. Please determine whether the two sequences can form the same binary search tree.
Output Description:
If the sequence is the same, YES is output, otherwise NO is output.
Example 1
input
2
567432
543267
576342
0
output
YES
NO
#include <iostream> #include <string> #include <cstring> using namespace std; struct node{ node * Lchild; node * Rchild; int num; }tree[205]; int loc,len; node * creat(){ tree[loc].Lchild=tree[loc].Rchild=NULL; return &tree[loc++]; } node * insert_node(node * t, int x){ if(t==NULL){ t=creat(); t->num=x; return t; } else if(x<t->num) t->Lchild=insert_node(t->Lchild,x); else if(x>t->num) t->Rchild=insert_node(t->Rchild,x); return t; } void preorder(node * t,char s[]){ s[len++]=t->num+'0'; if(t->Lchild) preorder(t->Lchild,s); if(t->Rchild) preorder(t->Rchild,s); } void midorder(node * t,char s[]){ if(t->Lchild) midorder(t->Lchild,s); s[len++]=t->num+'0'; if(t->Rchild) midorder(t->Rchild,s); } int main(){ int n; string str; char cmp1[21],cmp2[21]; while(cin>>n){ if(n==0) break; node * T = NULL; loc=0; cin>>str; for(int i=0;i<str.size();i++) T=insert_node(T,int(str[i]-'0')); len=0;preorder(T,cmp1);midorder(T,cmp1);cmp1[len]='\0'; while(n--){ node * T = NULL; cin>>str; for(int i=0;i<str.size();i++) T=insert_node(T,int(str[i]-'0')); len=0;preorder(T,cmp2);midorder(T,cmp2);cmp2[len]='\0'; if(strcmp(cmp1,cmp2)!=0) cout<<"NO"<<endl; else cout<<"YES"<<endl; } } return 0; }