團體程式設計天體賽(L3-010 是否完全二叉搜尋樹 (30 分))
阿新 • • 發佈:2021-11-10
題目:
思路分析:
可以通過陣列來模擬建樹過程
也可以‘真實‘建樹
判斷是否為完全二叉樹 只需要判斷點的個數是否==n
程式碼實現:
1 const int MAX=1000010; 2 struct node{ 3 node *l,*r; 4 int data; 5 }; 6 int n; 7 node *insert(node *root,int x){ 8 if(root==NULL){ 9 root=new node; 10 root->data=x; 11 root->l=root->r=NULL;12 return root; 13 } 14 else{ 15 if(root->data>x){ 16 root->r=insert(root->r,x); 17 } 18 else root->l=insert(root->l,x); 19 } 20 return root; 21 } 22 void print_ch(node *root){ 23 queue<node*>qu; 24 25 if(root){ 26 cout<<root->data; 27 qu.push(root); 28 } 29 while (!qu.empty()) { 30 node *now=qu.front(); 31 qu.pop(); 32 if(now->l){ 33 cout<<" "<<now->l->data; 34 qu.push(now->l); 35 } 36 if(now->r){ 37 cout<<" "<<now->r->data; 38 qu.push(now->r); 39 } 40 } 41 } 42 void check(node *root){ 43 queue<node*>qu; 44 qu.push(root); 45 int num=0; 46 while (qu.front()!=NULL) { 47 node *now=qu.front(); 48 qu.pop(); 49 qu.push(now->l); 50 qu.push(now->r); 51 num++; 52 } 53 if(n==num)cout<<"YES"; 54 else cout<<"NO"; 55 } 56 int main(){ 57 cin>>n; 58 node *root=NULL; 59 for(int i=0;i<n;i++){ 60 int x; 61 cin>>x; 62 root=insert(root,x); 63 } 64 print_ch(root); 65 cout<<endl; 66 check(root); 67 }
/* *@Author: GuoJinlong *@Language: C++ */ //#include <bits/stdc++.h> /* * __----~~~~~~~~~~~------___ * . . ~~//====...... __--~ ~~ * -. \_|// |||\\ ~~~~~~::::... /~ * ___-==_ _-~o~ \/ ||| \\ _/~~- * __---~~~.==~||\=_ -_--~/_-~|- |\\ \\ _/~ * _-~~ .=~ | \\-_ '-~7 /- / || \ / * .~ .~ | \\ -_ / /- / || \ / * / ____ / | \\ ~-_/ /|- _/ .|| \ / * |~~ ~~|--~~~~--_ \ ~==-/ | \~--===~~ .\ * ' ~-| /| |-~\~~ __--~~ * |-~~-_/ | | ~\_ _-~ /\ * / \ \__ \/~ \__ * _--~ _/ | .-~~____--~-/ ~~==. * ((->/~ '.|||' -_| ~~-/ , . _|| * -_ ~\ ~~---l__i__i__i--~~_/ * _-~-__ ~) \--______________--~~ * //.-~~~-~_--~- |-------~~~~~~~~ * //.-~~~--\ * ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ * * 神獸保佑 永無BUG */ const int MAX=10001; int a[MAX]; void built(int pos,int x){ if(a[pos]==-1){ a[pos]=x; return; } if(x>a[pos]){ built(pos*2,x); } else{ built(pos*2+1,x); } } int main(){ int n; cin>>n; mms(a,-1); for(int i=0;i<n;i++){ int x; cin>>x; built(1,x); } int pos=1; int t=0; while (t<n) { while (a[pos]==-1) { pos++; } if(pos==1) cout<<a[pos++]; else cout<<" "<<a[pos++]; t++; } cout<<endl; if(n+1==pos){ cout<<"YES"; } else cout<<"NO"<<endl; }