The Input
The input is a sequence of binary trees specified as described above. Each tree in a sequence consists of several pairs (n,s) as described above separated by whitespace. The last entry in each tree is (). No whitespace appears between left and right parentheses.
All nodes contain a positive integer. Every tree in the input will consist of at least one node and no more than 256 nodes. Input is terminated by end-of-file.
The Output
For each completely specified binary tree in the input file, the level order traversal of that tree should be printed. If a tree is not completely specified, i.e., some node in the tree is NOT given a value or a node is given a value more than once, then the string ``not complete'' should be printed.
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
not complete
问题描述:
根据输入(输入格式如上),若能构成树,则按广度搜索输出。不能,则输出”not complete“。
代码如下:
#include<iostream>
#include<queue>
#include<vector>
#include<cstdio>
#include<cstring>
using namespace std;
bool p=false;
struct Node
{
int v;
bool have_value; //判断结点里面是否有值。
Node* Lchild,*Rchild;
Node():have_value(false),Lchild(NULL),Rchild(NULL){} //构造函数
};
Node* NewNode(){return new Node();}
Node* root=NewNode();
void AddNode(Node*root,int &v,char*xs)
{
if(*xs=='L')
{
if(!root->Lchild)
root->Lchild=NewNode();
AddNode(root->Lchild,v,xs+1);
}
else if(*xs=='R')
{
if(!root->Rchild)
root->Rchild=NewNode();
AddNode(root->Rchild,v,xs+1);
}
else //当遇到‘)’时把值赋给相应的结点
{
if(root->have_value) //重复赋值时,说明树有错误。并用p记录
p=true;
root->have_value=true; //标记结点里面有值
root->v=v;
}
}
bool BFS(Node*root,vector<int>&ans) //广度优先搜索
{
queue<Node*>que;
if(root->have_value)
que.push(root);
else
return false;
while(!que.empty())
{
Node*pionter=que.front();
que.pop();
if(!pionter->have_value) return false;
ans.push_back(pionter->v);
if(pionter->Lchild!=NULL)
que.push(pionter->Lchild);
if(pionter->Rchild!=NULL)
que.push(pionter->Rchild);
}
return true;
}
void remove_tree(Node*root) //释放树的空间
{
if(root==NULL)return;
remove_tree(root->Lchild);
remove_tree(root->Rchild);
delete root;
}
int main()
{
char s[260],xs[260];
vector<int> ans;
int v;
while(~scanf("%s",s))
{
if(!strcmp(s,"()"))
{
if(p||!BFS(root,ans))
{
cout<<"not complete"<<endl;
::p=false; //重置p
remove_tree(root); //释放树的空间
::root=NewNode(); //重新建立根
ans.clear(); //别忘清空
}
else
{
for(int i=0;i<ans.size()-1;i++)
cout<<ans[i]<<" ";
cout<<ans[ans.size()-1]<<endl;
::p=false;
remove_tree(root);
::root=NewNode();
ans.clear();
}
}
else
{
sscanf(s,"(%d,%s",&v,xs); //取出里面的数值和位置 例:(4,LR)则v=4 xs="LR)"
AddNode(root,v,xs); //把该点添加到树上
}
}
return 0;
}