uva122解题报告
2015-12-29 13:23
363 查看
题意大致就是给你一棵树,然后你用层序遍历。每个节点的给出通过一个组合,(value, pos)pos是由LR组合而成。L代表一次左儿子,R为一次右儿子。输出时需要注意判断给的结点是否完整和重复。
解题思路: 1.不能用数组存储满二叉树。256个结点如果排成一个偏左树,那数组将非常非常大。行不通。所以用数组存储每一个输入的结点。
2. 总共4个数组 left数组存放当前结点的左儿子的结点在数组中的下标 right数组相对。 have_value 用来判断此结点是否有值(因为,我们输入结点时,如果他的父节点为空,则创建一个父节点,再往下走。但此时新的父节点是无值得)。 value数组存放值。
代码如下:
解题思路: 1.不能用数组存储满二叉树。256个结点如果排成一个偏左树,那数组将非常非常大。行不通。所以用数组存储每一个输入的结点。
2. 总共4个数组 left数组存放当前结点的左儿子的结点在数组中的下标 right数组相对。 have_value 用来判断此结点是否有值(因为,我们输入结点时,如果他的父节点为空,则创建一个父节点,再往下走。但此时新的父节点是无值得)。 value数组存放值。
代码如下:
#include <iostream> #include <cstring> #include <queue> using namespace std; const int MAXN = 3000; const int maxn = 100000; int lef[MAXN],righ[MAXN],have_value[MAXN], value[MAXN]; char s[maxn] = ""; const int root =1; int nCnt = 0; bool isFailed = false; // 用来标记输入是否有重复 void newTree() { lef[root] =0; righ[root] = 0; have_value[root] = false; isFailed = false; value[root] = 0; nCnt = 1; } int newNode() { int index = ++nCnt; lef[index] = righ[index] = 0; have_value[index] = false; return index; } void addNode(int val, char *pStr) { int index = root; for (int i =0;i<strlen(pStr);++i) { if (pStr[i] == 'L') { if (lef[index] == 0) lef[index] = newNode(); index = lef[index]; } else if (pStr[i] == 'R') { if (righ[index] == 0) righ[index] = newNode(); index = righ[index]; } } if(have_value[index]) isFailed = true; value[index] = val; have_value[index] = true; } bool bfs(vector<int> &ans/*存放结果*/) { queue<int> q; // int用来存放元素的下标 ans.clear(); q.push(root); while (!q.empty()) { int index = q.front();q.pop(); if (!have_value[index]) return false; ans.push_back(value[index]); if (lef[index]) q.push(lef[index]); if (righ[index]) q.push(righ[index]); } return true; } bool read() { newTree(); while(true) { if (scanf("%s", s) != 1) return false; if (!strcmp(s, "()")) break; int val; sscanf(&s[1], "%d", &val); addNode(val, strchr(s, ',')); } return true; } int main() { while (true) { if (!read()) break; if (isFailed) { cout<<"not complete"<<endl; continue; } vector<int> ans; if (!bfs(ans)) cout<<"not complete"<<endl; else { for (vector<int>::iterator i = ans.begin(); i!= ans.end();) { cout<< *i; if (++i != ans.end()) cout<<" "; } cout<<endl; } } return 0; }
相关文章推荐
- 【后缀自动机】[SPOJLCS]Longest Common Substring
- iOS 删除本地文件的方法
- RedHat ISO
- Android 下拉刷新控件SwipeRefreshLayout
- 最简配置 app 升级服务器
- 使UITextView不换行
- 011 关于指针只读和指针指向的对象只读
- #总结 2015.12.29
- 算法的时间复杂度和空间复杂度合称为算法的复杂度。
- Safe Or Unsafe--hdu2527(哈夫曼树求WPL)
- java 集合(2) 遍历collection集合方法 iterator / 加强型for循环
- Bootstrap不同级别标题
- asp+access数据库显示FROM字句有错误
- 转战Android Studio 三
- Mybatis3源码分析(22)-总结
- actionInvocation.invoke()是什么意思
- mysql生成随机数
- LeetCode之Backtracing题目汇总
- ajax
- Unity3D游戏开发从零单排(四) - 制作一个iOS游戏