UVA122TreesOnTheLevel
来源:互联网 发布:竞价推广软件 编辑:程序博客网 时间:2024/06/01 08:10
//UVA122#include<cstdio>#include<cstdlib>#include<cstring>#include<cctype>#include<queue>//#define LOCALusing namespace std;typedef struct TreeNode* TN;const int MAXN = 300;struct TreeNode {int data;TN left;TN right;}; char s[300];TN Create() {TN New = (TN)malloc(sizeof(struct TreeNode));New->data = -1;//-1代表空值 New->left = NULL;New->right = NULL;return New; }TN Search(TN head, char c) {if(c == 'L') return head->left;else if(c == 'R') return head->right; }void LevelTraversal(TN head) {//checkqueue<TN> Tnodes;Tnodes.push(head);int cnt = 0;while(!Tnodes.empty()) {//printf("cnt = %d\n", ++cnt);TN tmp = Tnodes.front(); Tnodes.pop();if(cnt++) printf(" ");printf("%d", tmp->data);if(tmp->left) Tnodes.push(tmp->left);if(tmp->right) Tnodes.push(tmp->right);}printf("\n");}bool check(TN head) {TN tmp = head;if(head == NULL) return true;if(head->data == -1) return false;return check(head->left) && check(head->right);}void Clear(TN head) {TN tmp = head;if(head->left || head->right) { free(head); return ;}else if(head->left == NULL)Clear(head->right);else if(head->right == NULL) Clear(head->left);else {Clear(head->left);Clear(head->right);}}int main() {while(1) {TN head = Create(); int flag = 0; #ifdef LOCAL freopen("UVA122in.txt", "r", stdin); freopen("UVA122out.txt", "w", stdout); #endif bool end = 1;while((scanf("%s", s)) == 1) { end = 0; int len = strlen(s); if(s[0] == '(' && s[1] == ')') {break; } if(s[len - 2] == ',') {//向头结点中插入数据 int tmp = 2, cnt = s[1] - '0', dec = 0; while(isdigit(s[tmp])) { cnt = cnt * 10 + s[tmp] - '0'; tmp++; } head->data = cnt; //printf("cnt = %d\n", cnt); } else { int cnt = 0; int i = 0; for(i = 1; s[i] != ','; i++) cnt = cnt * 10 + s[i] - '0'; //printf("cnt = %d\n", cnt); TN tmp = head, tmp1 = NULL; while(isalpha(s[++i])) { //printf("%c ", s[i]);// if(s[i] == 'L') { //向左走 if(!(tmp1 = Search(tmp, 'L'))) { //printf("************\n"); TN t = Create(); t->data = -1; t->left = t->right = NULL; tmp->left = t; tmp = t;}else tmp = tmp1;}else { //向右走 if(!(tmp1 = Search(tmp, 'R'))) {TN t = Create(); t->data = -1; t->left = t->right = NULL; tmp->right = t; tmp = t;}else tmp = tmp1;}}if(tmp->data != -1) { flag = 1; }tmp->data = cnt;} } if(end) return 0; if(flag || !check(head)) {//结点被重复赋值或有缺值点,则不满足输出要求 printf("not complete\n"); flag = 1;}if(!flag) LevelTraversal(head);//Clear(head); }return 0;}/*(11,LL) (7,LLL) (8,R)(5,) (4,L) (13,RL) (2,LLR) (1,RRR) (4,RR) ()(3,L) (4,R) ()*/
阅读全文
0 0