UVA 122 树的层次遍历
来源:互联网 发布:mac有的软件删不掉 编辑:程序博客网 时间:2024/06/07 20:03
这里使用数组来实现二叉树,用整数表示节点编号,left[u]和right[u]分别表示u节点的左孩子和右孩子的节点编号。
这里关键是按照输入建立出二叉树。
对应代码如下:
#include<cstdio>#include<iostream>#include<algorithm>#include<cstring>#include<string>#include<vector>#include<queue>using namespace std;const int maxn = 300;int Left[maxn], Right[maxn],Value[maxn];bool hasValue[maxn];int root;int cnt;bool failed;void newTree(){ cnt = 0; root = ++cnt; Left[root] = Right[root] = 0; hasValue[root] = false;}int newNode(){ ++cnt; Left[cnt] = Right[cnt] = 0; hasValue[cnt] = 0; return cnt;}void addnode(int v, char *s){ int t = root; for (int i = 0; i < strlen(s)-1; i++){ if (s[i] == 'L'){ if (Left[t] == 0) Left[t] = newNode(); t = Left[t]; } else{ if (Right[t] == 0) Right[t] = newNode(); t = Right[t]; } } if (hasValue[t]) failed = true; hasValue[t] = true; Value[t] = v;}bool getinput(){ char s[maxn]; failed = false; newTree(); for (;;){ if (scanf("%s", s) != 1) return false; if (!strcmp(s, "()")) break; int v; sscanf(&s[1], "%d", &v); addnode(v, strchr(s, ',') + 1); } return true;}void bfs(vector<int> &ans){ queue<int> q; ans.clear(); q.push(root); while (!q.empty()){ int p = q.front(); q.pop(); if (!hasValue[p]){ failed = true; return; } ans.push_back(Value[p]); if (Left[p] != 0) q.push(Left[p]); if (Right[p] != 0) q.push(Right[p]); } return;}int main(){ while (getinput()){ vector<int> ans; bfs(ans); if (failed) cout << "not complete" << endl; else{ cout << ans[0]; for (int i = 1; i < ans.size(); i++) cout << " " << ans[i]; cout << endl; } memset(hasValue, 0, sizeof(hasValue)); } 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)
- 树的层次遍历
- 树的层次遍历
- 树的层次遍历
- 形状识别之直线检测
- JS控制-图片滚动切换效果(实用)
- .net网页中插入Flash
- SPOJ3267 D-Query 树状数组离线操作 或 主席树 查询某一区间内有多少不同的数
- MVC3获取登录用户名
- UVA 122 树的层次遍历
- APS.netMVC的ViewModel问题
- [资料]aspnetdb.mdf数据库的建立和使用
- 机器学习教程之1-感知器(Perceptron)的sklearn实现
- spring 集成定时任务
- Membership、MembershipUser和Roles类
- MVC --- 创建一个实例化类的函数
- logback
- MVC3 网站发布问题(转发)