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

Problem Description

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

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

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

Sample Input

abc,de,g,f,

Sample Output

cbegdfa
cgefdba

Hint

Source
xam

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

int i;
char a[55];

struct tree
{
    struct tree *right,*left;
    char data;
};

struct tree * newroot()
{
    struct tree *root;
    root=(struct tree *)malloc(sizeof(struct tree));
    root->left=NULL;
    root->right=NULL;
    return root;
}

struct tree * creat()
{
    struct tree *t=newroot();
    if(a[i]==',')
    {
        i++;
        return NULL;
    }
    t->data=a[i];
    i++;
    t->left=creat();
    t->right=creat();
    return t;
}

void midshow(struct tree *t)
{
    if(t!=NULL)
    {
        midshow(t->left);
        printf("%c",t->data);
        midshow(t->right);
    }
}

void backshow(struct tree *t)
{
    if(t!=NULL)
    {
        backshow(t->left);
        backshow(t->right);
        printf("%c",t->data);
    }
}

int main()
{
    struct tree *root;
    while(~scanf("%s",a))
    {
        i=0;
        root=creat();
        midshow(root);
        printf("\n");
        backshow(root);
        printf("\n");
    }
    return 0;
}

猜你喜欢

转载自blog.csdn.net/weixin_44041997/article/details/86604090