https://uva.onlinejudge.org/index.php?option=com_onlinejudge&Itemid=8&page=show_problem&problem=58
题目
树是计算机科学很多分支的基础。(此处省略1万字)
本问题设计二叉树的构建和遍历。
给定一个二叉树的序列,你需要写一个程序输出按层次,从左到右,从上到下的顺序遍历树节点的权值。所有节点的权值都是正整数。所以二叉树都不会含有超过256个节点。比如下图(回原题看去):
遍历的结果为5 4 8 11 13 4 7 2 1
本题通过二元组的集合表示一个二叉树。二元组(n,s)
中,n表示该节点的权值,s表示从根节点到该节点的路径,L
表示走节点的左儿子,’R’表示走节点的右儿子。上图中,权值为13的节点的表示为(13,RL)
,权值为2的节点的表示为(2,LLR)
,根节点的表示为(5,)
,s为空字符串,表示哪里都不走,就是根节点。一个二叉树被认为是完整的仅当每个节点都被恰好赋过一次权值(赋值多次不行,没有赋值也不行)。
输入
输入有多组数据,由多个节点表示形如(n,s)
组成,最后以()
结尾表示该组数据结束。
节点表示内没有空格,每棵树至少有一个节点,不会超过256个节点。
输出
对于每组数据,输出一行。如果该树的每个节点都被恰好赋过一次权值,那么输出其按层次顺序遍历的序列,否则输出”not complete”。
样例输入
(11,LL) (7,LLL) (8,R)
(5,) (4,L) (13,RL) (2,LLR) (1,RRR) (4,RR) ()
(3,L) (4,R) ()
样例输出
5 4 8 11 13 4 7 2 1
not complete
题解
#include <cstdio>
#include <cstring>
#include <queue>
#include <vector>
using namespace std;
const int N = 100005;
int l[N], r[N], vis[N], val[N];
int id; bool failed;
void add_node(int &t, int v, char *s) {
if (t == 0) t = ++id;
if (*s == 0 || *s == ')') {
if (vis[t]) {
failed = true;
} else {
val[t] = v;
vis[t] = 1;
}
return;
}
if (*s == 'L') add_node(l[t], v, s + 1);
else if (*s == 'R') add_node(r[t], v, s + 1);
}
vector<int> *bfs(int root) {
vector<int> *res = new vector<int>();
queue<int> q;
q.push(root);
while (!q.empty()) {
int u = q.front();
q.pop();
if (!vis[u]) {
delete res;
return NULL;
}
res->push_back(val[u]);
if (l[u]) q.push(l[u]);
if (r[u]) q.push(r[u]);
}
return res;
}
int main() {
static char node_descriptor[N], location_descriptor[N];
int value, i, root;
while (true) {
id = 1; root = 0; failed = false;
memset(vis, 0, sizeof vis);
memset(l, 0, sizeof l);
memset(r, 0, sizeof r);
while (true) {
if (scanf("%s", node_descriptor) != 1) return 0;
if (node_descriptor[1] == ')') break;
sscanf(node_descriptor, "(%d,%s", &value, location_descriptor);
add_node(root, value, location_descriptor);
}
vector<int> *res = bfs(root);
if (res != NULL && !failed) {
if (res->size() > 0)
printf("%d", (*res)[0]);
for (i = 1; i < res->size(); ++i)
printf(" %d", (*res)[i]);
putchar('\n');
} else {
printf("not complete\n");
}
}
return 0;
}