https://vjudge.net/problem/UVA-122
学习的第一个关于树的题目,按着紫书上的思路来的。再整理一下
#include<iostream>
#include<cstdio>
#include<queue>
#include<cstring>
using namespace std;
struct Node{//结点的结构体
bool have_value;
int v;
Node *left,*right;
Node():have_value(false),left(NULL),right(NULL){}
};
vector<int> ans;
void addnode(int v,char* s);
Node * root;
bool failed;
Node*newnode(){return new Node();}
const int maxn = 300;
char s[maxn];
bool read_input(){ //读取数据
failed = false;
root = newnode();
for(;;)
{
if(scanf("%s",s) != 1)return false;//如果没有输入 跳出
if(!strcmp(s,"()"))break;
int v;
sscanf(&s[1],"%d",&v);
addnode(v,strchr(s,',')+1);//strchr :查找字符串s中首次出现字符c的位置。
}
return true;
}
void addnode(int v,char* s){//建树,添加结点 并在该节点赋值
int n = strlen(s);
Node* u = root;
for(int i = 0 ; i < n ; i++)
{
if(s[i] == 'L'){
if(u->left == NULL) u->left = newnode();
u = u->left;
}else if(s[i] == 'R'){
if(u->right == NULL) u-> right = newnode();
u = u ->right;
}
}
if(u -> have_value) failed = true;//如果有重复输入。该测试数据无效
u->v = v;
u->have_value = true;
}
bool bfs(){//遍历树,储存数据到ans向量中
queue<Node*> q;
ans.clear();
q.push(root);
while(!q.empty()){
Node* u = q.front(); q.pop();
if(!u->have_value)return false;//如果树不完整 该测试数据无效
ans.push_back(u->v);
if(u->left != NULL) q.push(u->left);
if(u->right != NULL) q.push(u->right);
}
return true;
}
int main()
{
while(read_input())
{
if(bfs()&&!failed){
for(vector<int>::iterator it = ans.begin();it!=ans.end();it++)
{
if(it!=ans.begin()) cout << " " ;
cout<<*it;
}
cout <<endl;
}
else{ cout <<"not complete"<<endl;}
}
return 0;
}