UVa122-Trees on the level
阿新 • • 發佈:2018-10-28
構建 max 二叉樹 .net print while 超過 stdin ack
1.題目描述:點擊鏈接
2.問題分析:
簡單地來說,就是輸入一組字符串,表示二叉樹上某些節點的值和位置,這些節點不一定可以組成一顆完整的二叉樹,可能出現缺少某個節點或者某個節點冗余的情況。
需要我們進行判斷是否能組成一顆完整的二叉樹,若可以按照由上到下,由左到右的順序輸出每個節點的值,若不能則輸出not complete
3.輸入數據分析:
題目上給出節點的個數不超過256個,如果按照最壞的情況去考慮,256個節點組成一條單鏈,那麽最後一個節點的編號會非常大,所以不能用暴力去解決。
4.算法設計:
由於節點的不確定,最好構建一個二叉樹,然後往樹裏添加新的節點,最後使用bfs查找是否存在缺少或者多余的情況。
5.代碼:
1 #include<iostream> 2 #include<vector> 3 #include<stdio.h> 4 #include<stdlib.h> 5 #include<cstring> 6 #include<queue> 7 #include<string.h> 8 using namespace std; 9 const int maxn=256+10; 10 char s[maxn]; 11 bool failed; 12 struct Node{ 13 intv; 14 bool have_value; 15 Node *left,*right; 16 Node():have_value(false),left(NULL),right(NULL){} 17 }; 18 Node *root; 19 Node *newnode(){return new Node();} 20 void addnode(int v,char *s){ 21 int n=strlen(s); 22 Node *u=root; 23 for(int i=0;i<n;i++) 24 { 25 if(s[i]==‘L‘){ 26 if(u->left==NULL)u->left=newnode(); 27 u=u->left; 28 } 29 else if(s[i]==‘R‘){ 30 if(u->right==NULL)u->right=newnode(); 31 u=u->right; 32 } 33 } 34 if(u->have_value==1) failed=true; 35 u->have_value=1; 36 u->v=v; 37 } 38 bool read_input(){ 39 failed=false; 40 root=newnode(); 41 for(;;){ 42 if(scanf("%s",s)==EOF)return false; 43 if(strcmp(s,"()")==0)break; 44 int v; 45 sscanf(&s[1],"%d",&v); 46 addnode(v,strchr(s,‘,‘)+1); 47 } 48 return true; 49 } 50 bool bfs(vector<int>&ans){ 51 queue<Node*>q; 52 ans.clear(); 53 q.push(root); 54 while(!q.empty()){ 55 Node* u=q.front();q.pop(); 56 if(!u->have_value)return false; 57 ans.push_back(u->v); 58 if(u->left!=NULL)q.push(u->left); 59 if(u->right!=NULL)q.push(u->right); 60 } 61 return true; 62 } 63 int main() 64 { 65 freopen("in.txt","r",stdin); 66 while(1) 67 { 68 if(read_input()==0)break; 69 vector<int>ans; 70 if(!failed&&bfs(ans)){ 71 int n=ans.size(); 72 for(int i=0;i<n;i++) 73 printf("%d%c",ans[i],i==n-1?‘\n‘:‘ ‘); 74 } 75 else{ 76 printf("not complete\n"); 77 } 78 } 79 return 0; 80 }
UVa122-Trees on the level