uva 122 Trees on the level 二叉树的层次遍历(bfs)
2016-08-21 21:27
441 查看
题目链接
#include<cstring> #include<string> #include<cstdio> #include<cstdlib> #include<iostream> #include<cmath> #include<algorithm> #include<queue> #include<vector> #include<map> #include<stack> #include<climits> #include<cctype> #include<bitset> #include<set> using namespace std; #define mod 1000000007 #define PI acos(-1.0) #define INF 0x3f3f3f3f typedef long long LL; char s[50]; bool failed; struct Node{ bool have_value; int v; Node *left,*right; Node():have_value(0),left(NULL),right(NULL){} }; Node *root; Node* newnode(){return new Node();} void addnode(int v,char* s){ int n=strlen(s); Node* u=root; for(int i=0;i<n;i++){ if(s[i]=='L'){ if(u->left==NULL)u->left=newnode(); u=u->left; } else if(s[i]=='R'){ if(u->right==NULL)u->right=newnode(); u=u->right; } } if(u->have_value)failed=1; u->v=v; u->have_value=1; } bool read_input(){ failed=0; root=newnode(); while(1){ if(scanf("%s",s)!=1)return 0; if(!strcmp(s,"()"))break; int v; sscanf(s+1,"%d",&v); addnode(v,strchr(s,',')+1); } return 1; } bool bfs(vector<int>& ans){ queue<Node*>q; ans.clear(); q.push(root); while(!q.empty()){ Node* u=q.front();q.pop(); if(!u->have_value)return 0; ans.push_back(u->v); if(u->left!=NULL)q.push(u->left); if(u->right!=NULL)q.push(u->right); } return 1; } int main() { while(read_input()){ if(failed)cout<<"not complete"<<endl; else { vector<int>ans; if(!bfs(ans)){ cout<<"not complete"<<endl; } else { printf("%d",ans[0]); for(int i=1;i<ans.size();i++){ printf(" %d",ans[i]); } cout<<endl; } } } return 0; }
相关文章推荐
- UVA 122 Trees on the level 二叉树层次遍历 数组&指针
- UVa 122 Trees on the level(链式二叉树的建立和层次遍历)
- UVa 122 Trees on the level(二叉树层次遍历)
- UVa 122 Trees on the level 建立二叉树BFS层序遍历
- UVA 122 Trees on the level (二叉树层次遍历)
- 例题6-7 二叉树的层次遍历 UVa 122 Trees on the level
- UVa 122 (二叉树的层次遍历) Trees on the level
- UVA122 Trees on the level【二叉树】【BFS】
- [UVA 122] Trees on the level 二叉树好难+BFS
- UVA.122 Trees on the level(二叉树 BFS)
- 例题6-7 UVA 122 - Trees on the level 树的层次遍历
- UVa 122 - Trees on the level【二叉树初接触(BFS)】
- Trees on the level UVA - 122 复习二叉树建立过程,bfs,queue,strchr,sscanf的使用。
- UVa 122 Trees on the level(建树,层次遍历)
- 例题6-7 树的层次遍历(Trees on the level, Duke 1993, UVa 122)
- UVA122 trees on the level(BFS)
- 例题6-7 UVa122 Trees on the level(树&&队列BFS&&sscanf字符串转整数)
- (二叉树)UVA - 122 Trees on the level
- UVA 122 Trees on the level 二叉树
- Trees on the level(UVA122,二叉树的建立)