SDUT-3441_数据结构实验之二叉树二:遍历二叉树

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

Time Limit: 1000 ms Memory Limit: 65536 KiB

Problem Description

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

Input

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

Output

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

Sample Input

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

Sample Output

cbegdfa
cgefdba

PS:如果对二叉树的遍历没有了解的话请先看我的另一篇博客 二叉树的四种遍历方式

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

typedef struct tree//树的节点
{
    char data;
    struct tree *l,*r;
}tree;

int i;
char s[55];

tree *newtree()//开辟新节点
{
    tree *t;
    t = (tree*)malloc(sizeof(tree));
    t->l = t->r = NULL;
    return t;
}

tree *creat()//根据给出的字符串建树
{
    tree *t = newtree();
    if(s[i++]==',')
        return NULL;
    t->data = s[i-1];
    t->l = creat();
    t->r = creat();
    return t;
}

void show_mid(tree *t)//中序遍历
{
    if(t)
    {
        show_mid(t->l);
        printf("%c",t->data);
        show_mid(t->r);
    }
}

void show_back(tree *t)//后序遍历
{
    if(t)
    {
        show_back(t->l);
        show_back(t->r);
        printf("%c",t->data);
    }
}

int main()
{
    tree *t;
    while(scanf("%s",s)!=EOF)
    {
        i = 0;
        t = newtree();
        t = creat();
        show_mid(t);
        printf("\n");
        show_back(t);
        printf("\n");
    }
    return 0;
}

猜你喜欢

转载自www.cnblogs.com/luoxiaoyi/p/9842798.html