数据结构实验之二叉树五:层序遍历

来源:互联网 发布:a卡10.13 hdmi mac 编辑:程序博客网 时间:2024/06/07 01:24
Problem Description已知一个按先序输入的字符序列,如abd,,eg,,,cf,,,(其中,表示空结点)。请建立二叉树并求二叉树的层次遍历序列。Input 输入数据有多行,第一行是一个整数t (t<1000),代表有t行测试数据。每行是一个长度小于50个字符的字符串。 Output 输出二叉树的层次遍历序列。 Example Input2abd,,eg,,,cf,,,xnl,,i,,u,,Example OutputabcdefgxnuliHint


#include<stdio.h>#include<stdlib.h>#include<iostream>using namespace std;typedef struct BiTNode{char data;struct BiTNode *lchild,*rchild;}BiTNode,*BiTree;char ch[51];int cnt;BiTree creat(){BiTNode *T;if(ch[++cnt]==',')T=NULL;else{T=new BiTNode;T->data=ch[cnt];T->lchild=creat();T->rchild=creat();}return T;}void Level(BiTree T){    BiTree p[110];    int pu = 0,po = 0;    p[pu++] = T;    while(pu > po)    {        if(p[po])        {            printf("%c",p[po]->data);            p[pu++] = p[po]->lchild;            p[pu++] = p[po]->rchild;        }        po++;    }}int main(){int i,j,n,m,k,t;BiTree T;while(scanf("%d",&n)!=EOF){for(i=0;i<n;i++){scanf("%s",ch);cnt=-1;T=new BiTNode;T=creat();Level(T);printf("\n");}}return 0;}