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

来源:互联网 发布:linux备份系统 编辑:程序博客网 时间:2024/06/06 16:37

数据结构实验之二叉树二:遍历二叉树
Time Limit: 1000MS Memory Limit: 65536KB
Submit Statistic Discuss
Problem Description

已知二叉树的一个按先序遍历输入的字符序列,如abc,,de,g,,f,,, (其中,表示空结点)。请建立二叉树并按中序和后序的方式遍历该二叉树。
Input

连续输入多组数据,每组数据输入一个长度小于50个字符的字符串。
Output

每组输入数据对应输出2行:
第1行输出中序遍历序列;
第2行输出后序遍历序列。

Example Input

abc,,de,g,,f,,,
Example Output

cbegdfa
cgefdba
Hint

Author

xam

#include<stdio.h>#include<stdlib.h>typedef struct node{    char data;    struct node *lchild;    struct node *rchild;}bintreenode;char ch[51];int flag;bintreenode *create(){    bintreenode *t;    if(ch[flag++] == ',')    {        t = NULL;    }    else    {        t = (bintreenode *)malloc(sizeof(bintreenode));        t->data = ch[flag-1];        t->lchild = create();        t->rchild = create();    }    return t;}void xianxu(bintreenode *t){    if(t!=NULL)    {        printf("%c",t->data);        xianxu(t->lchild);        xianxu(t->rchild);    }}void zhongxu(bintreenode *t){    if(t!=NULL)    {        zhongxu(t->lchild);        printf("%c",t->data);        zhongxu(t->rchild);    }}void houxu(bintreenode *t){    if(t!=NULL)    {        houxu(t->lchild);        houxu(t->rchild);        printf("%c",t->data);    }}int main(){    while(~scanf("%s",ch))    {        flag = 0;        bintreenode *t;        t = create();        //xianxu(t);        //printf("\n");        zhongxu(t);        printf("\n");        houxu(t);        printf("\n");    }}
0 0
原创粉丝点击