解题思路:首先要根据输入的字符串构建二叉树,然后利用BFS层次遍历二叉树,注意sscanf和BFS在二叉树遍历中的应用,尤其关注代码中的注释!该代码并不完全,没有对非法的二叉树输入进行处理。仅仅作为层次遍历的参考。
题目描述:Given a sequence of binary trees, you are to write a program that prints a level-order traversal of each tree. In this problem each node of a binary tree contains a positive integer and all binary trees have have fewer than 256 nodes.
给定一个二叉树序列,你要写一个程序将每棵树按层序访问并打印出来。在这个问题中,二叉树的每个节都值都为正整数,且每棵树的节点数都小于256。
In a level-order traversal of a tree, the data in all nodes at a given level are printed in left-to-right order and all nodes at level k are printed before all nodes at level k+1.
在层序遍例一个树时,指定行中所有的结点应按照从左至右的顺序打印,并且在第k行打印完之后才能打印第k+1行。
For example, a level order traversal of the tree
比如,按层序遍例下面的树的结果是:
is: 5, 4, 8, 11, 13, 4, 7, 2, 1.
Sample Input
输入示例
(11,LL) (7,LLL) (8,R)
(5,) (4,L) (13,RL) (2,LLR) (1,RRR) (4,RR) ()
(3,L) (4,R) ()
Sample Output
输出示例
5 4 8 11 13 4 7 2 1
not complete
#include<cstdio>
#include<queue>
#include<vector>
#include<string.h>
using namespace std;
struct node
{
bool have_value;
int v;
node *left,*right;
node():have_value(false),left(NULL),right(NULL){} //构造函数的形式一定注意!
};
char s[10];
node *root;
void addnode(int v,char s[]) //加入节点构建二叉树
{
node *u=root;
int n=strlen(s);
for(int i=0;i<n;i++) //循环次数与插入深度成正比
{
if(s[i]=='L') //插入左边
{
if(u->left==NULL)
{
u->left=new node();
}
u=u->left;
}
else if(s[i]=='R') //插入右边
{
if(u->right==NULL)
{
u->right=new node();
}
u=u->right;
}
}
u->have_value=true;
u->v=v; //到了设定的深度赋值
return;
}
void readnum()
{
root=new node();
while(scanf("%s",s)!=EOF)
{
if(strcmp(s,"()")==0) break;
int v; //存放字符串里的数值
sscanf(&s[1],"%d",&v); //sscanf的用法注意
addnode(v,strchr(s,',')+1);
}
return;
}
vector<int> ans; //存放最终结果的队列
void BFS() //BFS层次遍历二叉树
{
ans.clear();
queue<node *>Q; //利用队列BFS
Q.push(root);
while(Q.empty()==false)
{
node *tmp=Q.front();
Q.pop();
ans.push_back(tmp->v);
if(tmp->left!=NULL)
Q.push(tmp->left);
if(tmp->right!=NULL)
Q.push(tmp->right);
}
return;
}
int main()
{
while(1)
{
readnum();
BFS();
for(int i=0;i<ans.size();i++)
{
printf("%d ",ans[i]);
}
}
return 0;
}