HDU - 3791 :二叉搜尋樹
阿新 • • 發佈:2018-11-14
///這道題做了兩個小時,除錯了1個多小時,要補指標了,蒟蒻 #include<iostream> #include<cstdio> #include<cstring> #include<cstdlib> #include<algorithm> #define per(i,a,b) for(int i=a;i<b;i++) #define rep(i,b,a) for(int i=b;i>a;i--) using namespace std; struct node{ int key; node *l,*r,*p; }; int n; node *NIL; node *root; int des[11],st[11]; int sum=0; void insert1(int k){ node *x=root; node *y=NIL; node *z; z=(node*)malloc(sizeof(node)); z->key=k; z->l=NIL; z->r=NIL; z->p=NIL; while(x!=NIL){ y=x; if(z->key<x->key){ x=x->l; } else{ x=x->r; } } z->p=y; if(y==NIL) root=z; else { if(z->key<y->key){ y->l=z; } else y->r=z; } } void preorder0(node *root){ if(root==NIL) return; des[sum++]=root->key; preorder0(root->l); preorder0(root->r); } void preorder1(node *root){ if(root==NIL) return; st[sum++]=root->key; preorder1(root->l); preorder1(root->r); } bool Is_Same(){ per(i,0,sum){ if(des[i]!=st[i])return false; } return true; } int main(){ ios::sync_with_stdio(false); while((cin>>n)&&n){ char ch0[11]; memset(des,0,sizeof(des)); for(int i=0;i<=n;i++){ sum=0; memset(st,0,sizeof(st)); memset(ch0,0,sizeof(ch0)); cin>>ch0; for(int j=0;ch0[j]!='\0';j++){ int ch=ch0[j]-'0'; insert1(ch); } if(i==0){ preorder0(root); } else{ preorder1(root); if(Is_Same()){ cout<<"YES"<<endl; } else { cout<<"NO"<<endl; } } root=NIL; } } return 0; }