uva 122 树的层次遍历
来源:互联网 发布:数组splice 删除 编辑:程序博客网 时间:2024/06/03 18:25
#include<iostream>#include<iomanip>#include<algorithm>#include<cstdio>#include<cstdlib>#include<cmath>#include<map>#include<vector>#include<set>#include<queue>#include<cstring>using namespace std;const int maxn =256+10;char s[maxn];struct Node{ int v; bool have_value; Node* left; Node* right; Node():have_value(false),left(NULL),right(NULL) {};};Node* root;//根节点,使用前要申请空间bool failed;//记录是否有误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=true;//已经赋值过了,说明有误 u->v=v; u->have_value=true;//标记为已经赋值}bool readin(){ failed=false; while(1) { if(scanf("%s",s)!=1) return false;//输入非正常结束 if(!strcmp(s,"()")) break;//输入正常结束 int v; sscanf(&s[1],"%d",&v);//sscanf用法:将字符串s[1]中的整数写道v中; addnode(v,strchr(s,',')+1);//strchr用法:将s中第一次找到','的地址返回; } return true;}bool bfs(vector<int>& ans){ queue<Node*> q;//借助queue进行辅助,这是核心; ans.clear(); q.push(root); while(!q.empty()) { Node* u=q.front(); q.pop(); if(!u->have_value) return false; ans.push_back(u->v); if(u->left!=NULL) q.push(u->left); if(u->right!=NULL) q.push(u->right); } return true;}int main(){ while(1) { root=newnode(); if(!readin()) break; vector<int> ans;//用ans存储结果 if(!failed&&bfs(ans)) { int len=ans.size(); for(int i=0;i<len;++i) printf("%d%c",ans[i],i==len-1?'\n':' '); } else puts("not complete"); } return 0;}
0 0
- uva-122 树的层次遍历
- UVA 122 树的层次遍历
- UVA 122 树的层次遍历
- uva 122 树的层次遍历
- UVA 122 树的层次遍历
- uva-122 树的层次遍历
- 例题 6-7 树的层次遍历 UVa 122 建树+宽度优先遍历
- Uva 11234 Expressions (二叉树的层次遍历)
- UVA 122 Trees on the level (二叉树层次遍历)
- 例题6-7 UVA 122 - Trees on the level 树的层次遍历
- uva 122 Trees on the level 二叉树的层次遍历(bfs)
- Trees on the level 树的层次遍历 UVA 122(BFS)
- 紫书章六例题七 树的层次遍历 UVA 122(链表)
- 例题6-7 二叉树的层次遍历 UVa 122 Trees on the level
- 例题6-7 树的层次遍历(Trees on the level, Duke 1993, UVa 122)
- 树的层次遍历
- 树的层次遍历
- 树的层次遍历
- innodb存储引擎学习笔记
- 深度探索 OpenStack Neutron:Neutron 实现模型
- Matrices with XOR property
- LC_COLLATE is a variable which determines the collation order
- caffe 进行简单的训练和测试
- uva 122 树的层次遍历
- C# 获取内网或公网IPAddress
- 归园田居·其一
- JDK 8中Lambda研究
- STL中的hashtable
- 油脂
- Java中==与equals方法的区别
- IO多路复用——select()
- 如何启动/停止/重启MySQL