https://vjudge.net/problem/HDU-3791#
This is the first the time I write the Binary Search Tree by my self
I use the dfs to judge weather the two tree are same
and another methord if the prufer
The code of AC:
#include<bits/stdc++.h> using namespace std; int A[100],B[100]; const int inf=1<<30; struct BST{ int l,r,val,dat; }a[100]; int tot=0,root=0,Tot=0; int New(int val){ a[++tot].val=val; return tot; } void Build(){ memset(a,0,sizeof a); tot=0; New(-inf),New(inf); root=1,a[1].r=2; } void Insert(int &p,int val){ if(p==0){ p=New(val); return; } if(a[p].val<val) Insert(a[p].l,val); else Insert(a[p].r,val); } void dfs(int p){ if(p==0) return; A[++Tot]=a[p].val; dfs(a[p].l); dfs(a[p].r); A[++Tot]=a[p].val; } void dfs2(int p){ if(p==0) return; B[++Tot]=a[p].val; dfs2(a[p].l); dfs2(a[p].r); B[++Tot]=a[p].val; } int main(){ int n; while(cin>>n&&n){ string s; cin>>s; Build(); for(int i=0;i<s.length();++i){ Insert(root,s[i]-'0'); } memset(A,0,sizeof A); Tot=0; dfs(root); while(n--){ cin>>s; Build(); for(int i=0;i<s.length();++i){ Insert(root,s[i]-'0'); } Tot=0; memset(B,0,sizeof B); dfs2(root); int ans=1; for(int i=0;i<22;++i){ if(A[i]!=B[i]){ ans=0; } } if(ans) cout<<"YES"<<endl; else cout<<"NO"<<endl; } } }