(http://acm.hdu.edu.cn/showproblem.php?pid=1622)
#include <algorithm>
#include <iostream>
#include <cstdlib>
#include <cstring>
#include <cstdio>
#include <cmath>
#include<conio.h>
using namespace std;
typedef struct tnode
{
int V;
tnode* L;
tnode* R;
}tree;
tree node[300];
tree* root;
int tree_size,complete;
int test(tree* root) //检测树的完整性
{
if(!root->V) return 0;
int ans = 0;
if (!root->L || test(root->L)) //要么没有左孩子,要么有左孩子且左子树完整
ans++; //或语句:第一个条件符合则不判断第二个
if (!root->R || test(root->R)) //要么没有右孩子,要么有右孩子且右子树完整
ans++;
return ans == 2;
}
void madetree(tree *root, char* str, int v)
{
if (*str == 'R') {
if (!root->R)
root->R = &node[++tree_size];
//如果当前节点没有右指针,则给一个右指针,因为下一条madetree需要一个右指针 ,这样才能继续建树
madetree(root->R, str+1, v);
}else if (*str == 'L') {
if (!root->L)
root->L = &node[++tree_size];
//如果当前节点没有左指针,则给一个左指针,因为下一条madetree需要一个左指针 ,这样才能继续建树
madetree(root->L, str+1, v);
}else {
if (root->V)
complete = 0;
root->V = v;//给当前节点数据域赋值
}
}
tree* Q[300];
void output(tree *root) //层序遍历输出
{
int behind = 0,front = 0;//一个指针在前,一个指针在后
Q[front++] = root;
printf("%d",root->V);
while(behind < front) {
tree* now = Q[behind++];
if (now->L) {
printf(" %d",now->L->V);
Q[front++] = now->L;
}
if (now->R) {
printf(" %d",now->R->V);
Q[front++] = now->R;
}
}printf("\n");
}
int main()
{
char buf[256],leaf[256];
int value;
complete = 1;
root = &node[tree_size = 0];
while (~scanf("%s",buf)) {
if (!strcmp(buf,"()")) {
if (!complete || !test(root))
printf("not complete\n");
else output(root);
memset(node, 0, sizeof(node));
root = &node[tree_size = 0];
complete = 1;
}else {
sscanf(buf,"(%d,%s)",&value,leaf);
madetree(root, leaf, value);
}
}
getch();
return 0;
}