点击打开题目链接
层序遍历输出二叉树节点值。
存储结构可以是结构体+指针,也可以数组+下标
lrj代码对字符串的处理比较灵活。
代码:
#include<bits/stdc++.h>
using namespace std;
const int maxn = 256 + 5;
const int root = 1;
vector<int>ve;
int l[maxn], r[maxn];
int cnt;
int val[maxn], have_val[maxn];
char s[maxn];
int failed;
void newtree() {
l[root] = r[root] = 0;
have_val[root] = 0;
cnt = root;
}
int newnode() {
int u = ++cnt;
l[u] = r[u] = 0;
have_val[u] = 0;
return u;
}
void addnode(int v, char str[]) {
int len = strlen(str);
int u = root;
for(int i = 0; i < len; i++) {
if(str[i] == 'L') {
if(l[u] == 0) l[u] = newnode();
u = l[u];
}
else if(str[i] == 'R') {
if(r[u] == 0) r[u] = newnode();
u = r[u];
}
}
if(have_val[u]) failed = 1;
val[u] = v;
have_val[u] = 1;
}
int read_input() {
failed = 0;
newtree();
for(;;) {
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;
}
int bfs(vector<int>& ve) {
ve.clear();
queue<int> q;
q.push(root);
while(!q.empty()) {
int t = q.front(); q.pop();
if(!have_val[t]) return 0;
ve.push_back(val[t]);
if(l[t]) q.push(l[t]);
if(r[t]) q.push(r[t]);
}
return 1;
}
int main() {
//ios::sync_with_stdio(false);
while(read_input()) {
if(failed == 1) printf("not complete\n");
else {
int t = bfs(ve);
if(t == 0) printf("not complete\n");
else {
for(int i = 0; i < ve.size(); i++) {
if(i == 0) printf("%d",ve[i]);
else printf(" %d", ve[i]);
}
puts("");
}
}
}
return 0;
}