题目链接:http://acm.hit.edu.cn/hoj/problem/view?id=1168
刘汝佳《算法竞赛入门经典》101页的原题,层序遍历一棵树即可。
本题实际上联系字符串处理上面,直接使用strchr()字符串即可,strchr(s,',')返回字符串s中从左往右第一个字符','的指针。
#include <iostream>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <math.h>
#include <vector>
#include <queue>
#include <algorithm>
using namespace std;
#define len 100
#define Maxn 300
char s[len];
struct Node
{
int have_value;
int value;
Node * left;
Node * right;
};
Node * root;
int failed = 0;
Node * newNode()
{
Node * u = new Node;
u->have_value = 0;
u->left = NULL;
u->right = NULL;
return u;
}
void addNode(int value,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 == 1) failed = 1;
u->value = value;
u->have_value = 1;
}
vector <int> ans;
bool bfs()
{
ans.clear();
queue<Node*> q;
q.push(root);
while(!q.empty())
{
Node * temp = q.front();
q.pop();
if(temp->have_value == 0)
{
return false;
}
ans.push_back(temp->value);
if(temp->left!=NULL) q.push(temp->left);
if(temp->right!=NULL) q.push(temp->right);
}
return true;
}
int main()
{
#ifndef ONLINE_JUDGE
freopen("in.txt","r",stdin);
#endif
while(scanf(" %s",s)!=EOF)
{
int v;
failed = 0;
root = newNode();
while(strcmp(s,"()")!=0)
{
sscanf(&s[1],"%d",&v);
addNode(v,strchr(s,',')+1);
scanf(" %s",s);
}
if(failed == 1) printf("not complete\n");
else
{
if(bfs())
{
for(int i=0; i<ans.size(); i++)
{
if(i!=ans.size()-1) printf("%d ",ans[i]);
else printf("%d\n",ans[i]);
}
}
else
{
printf("not complete\n");
}
}
}
return 0;
}