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

来源:互联网 发布:怎样购买spycall软件 编辑:程序博客网 时间:2024/06/07 03:07

Problem Description

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

Input

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

Output

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

 

Example Input

abc,,de,g,,f,,,

Example Output

cbegdfacgefdba


#include<stdio.h>
#include<stdlib.h>
#include<string.h>
char str[51];
int i;
struct node
{
    char data;
    struct node *l,*r;
}binode;
struct node *cre()
{
    struct node *t;
    i++;
    if(str[i]==',')
        t=NULL;
    else
    {
        t=(struct node *)malloc(sizeof(struct node));
        t->data=str[i];
        t->l=cre();
        t->r=cre();
    }
    return t;
}
void mid(struct node *t)
{
    if(t)
    {
        mid(t->l);
        printf("%c",t->data);
        mid(t->r);
    }
}
void rear(struct node *t)
{
    if(t)
    {
        rear(t->l);
        rear(t->r);
        printf("%c",t->data);
    }
}
int main()
{
    while(~scanf("%s",str))
    {
        i=-1;
        struct node *root;
        root=cre();
        mid(root);
        printf("\n");
        rear(root);
        printf("\n");
    }
    return 0;
}

阅读全文
0 0