题意:

给定一颗树, 按层次遍历输出。

UVa 122 树的层次遍历-LMLPHP

分析:

用数组模拟二叉树, bfs即可实现层次遍历

 #include <bits/stdc++.h>
using namespace std;
struct Node{
bool have_value;
int v, left, right;
void reset(){//用于再次初始化节点
init();
}
void init(){
have_value = ;
v = left = right = ;
}
Node():have_value(false), v(),left(), right(){init();}//构造函数
};
const int maxn = ;
Node tree[maxn];
const int root = ;
int cnt, failed;
char s[maxn];
void newtree(){
cnt = ;
tree[root].reset();
}
void addnode(int v, char* s){ int len = strlen(s) - ;
int u = root;
for(int i = ; i < len; i++){
if(s[i] == 'L'){
if(tree[u].left == )
{
tree[u].left = ++cnt;
tree[cnt].reset();
u = cnt;
}
else { u = tree[u].left;};
}
else if(s[i] == 'R'){
if(tree[u].right == ){
tree[u].right = ++cnt;
tree[cnt].reset();
u = cnt;
}
else u = tree[u].right;
}
}
if(tree[u].have_value) failed = true;
tree[u].v = v;
tree[u].have_value = true;
}
bool input(){
newtree();
failed = false;
for(;;){
if(scanf("%s",s) != ) return false;
if(!strcmp(s,"()")) break;
int v;
sscanf(&s[],"%d",&v);
addnode(v,strchr(s,',')+);//将逗号后的字符串传递
}
return true;
}
bool bfs(vector<int>& ans){//引用传递
queue<int> q;
q.push(root);
while(!q.empty()){
int u = q.front();
q.pop();
if(tree[u].have_value == )
return false;
ans.push_back(tree[u].v);
if(tree[u].left != ){
q.push(tree[u].left);
}
if(tree[u].right != ){
q.push(tree[u].right);
}
}
return true;
}
int main(){ while(input()){
vector<int> ans;
if(!bfs(ans) || failed)
printf("not complete\n");
else {
cout <<ans[];
int alen = ans.size();
for(int i = ; i < alen; i++){
cout << " " << ans[i];
}
puts("");
}
}
return ;
}
05-11 13:23