openjudge 重建二叉树3

来源:互联网 发布:google java style 编辑:程序博客网 时间:2024/06/05 19:37

重建二叉树3

查看 提交 统计 提问

总时间限制: 1000ms 内存限制: 65535kB

描述

给出一颗二叉树每层节点的字符串表示,建立这颗二叉树,并输出中序遍历的结果。

 

输入

第一行输入一个整数t,代表测试数据的组数。

对于每组测试数据,第一行输入一个整数n,代表二叉树一共有几层。

随后输入的1n行,每行包含一个字符串S, 代表当前层从左到右的节点,字符为*表示该位置没有节点。从第二层起,每一层字符串的长度应是上一层的2倍。

输出

每组测试数据,输出一行,对应二叉树的中序遍历结果。

样例输入

2

3

A

CD

*EF*

4

A

BC

D*FG

*E******

样例输出

CEAFD

DEBAFCG

#include<iostream>using namespace std;#include<stdio.h>#include<malloc.h>#include<string.h>#include<stdlib.h>#define MaxSize 1000typedef char ElemType;typedef struct Nodes{ElemType data;int d;                     //用来记录左右,0左1右    int deepth;                //记录层次struct Nodes *lchild;struct Nodes *rchild;}BTreeNode;int A(BTreeNode *t){    printf("%c",t ->data);    if(t ->lchild != NULL)        A(t ->lchild);    if(t ->rchild != NULL)        A(t ->rchild);    return 0;}int B(BTreeNode *t){    if(t ->lchild != NULL)        B(t ->lchild);    printf("%c",t ->data);    if(t ->rchild != NULL)        B(t ->rchild);    return 0;}int C(BTreeNode *t){    if(t ->lchild != NULL)        C(t ->lchild);    if(t ->rchild != NULL)        C(t ->rchild);    printf("%c",t ->data);    return 0;}bool TextCreateTree(BTreeNode *&h){    int nc,i,j;    int state = 0;    char temp[MaxSize];    BTreeNode *qu[MaxSize],*p;    int front,rear;    front = rear = -1;    scanf("%d",&nc);    for(i = 0; i < nc; i++)    {        scanf("%s",temp);        getchar();        for(j = 0; temp[j] != '\0'; j++)        {            p = (BTreeNode *)malloc(sizeof(BTreeNode));            if(i == 0 && j == 0)            {                h = p;            }            p ->d = 0;            p ->data = temp[j];            p ->deepth = i;            p ->lchild = p->rchild = NULL;            if(p->data == '*')                p = NULL;            if(((rear)+MaxSize)%MaxSize + 1 == front)            {                printf("error");                exit(0);            }            qu[((++rear)+MaxSize)%MaxSize] = p;            if(i == 0)             {                continue;            }            if(qu[front + 1] != NULL)            {                if(state == 0)                {                    qu[front + 1] ->lchild = p;                    state++;                }                else if(state == 1)                {                    qu[front + 1] ->rchild = p;                    state++;                }                     }            else            {                state++;            }            if(state == 2)            {                state = 0;                front++;            }        }       }return 0;}int main(){    int n;    scanf("%d",&n);    getchar();        while(n--)    {        BTreeNode *h;        TextCreateTree(h);        B(h);        printf("\n");    }    return 0;}


0 0
原创粉丝点击