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

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

Time Limit: 1000 ms Memory Limit: 65536 KiB

Submit Statistic

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>
char pre[55];
int l;

typedef struct node
{
    char data;
    struct node *left;
    struct node *right;
}tree;

tree *creat()
{
    tree *root;
    char p;
    p=pre[l++];
    if(p==',')
        return NULL;
    else
    {
        root=(tree *)malloc(sizeof(tree));
        root->data=p;
        root->left=creat();
        root->right=creat();
    }
    return root;
};//建树

void postorder(tree *root)//后序
{
    if(root)
    {
        postorder(root->left);
        postorder(root->right);
        printf("%c",root->data);
    }
}

void inorder(tree *root)//中序
{
    if(root)
    {
        inorder(root->left);
        printf("%c",root->data);
        inorder(root->right);

    }
}


int main()
{
    int n;
    while(~scanf("%s",pre))
    {
        l=0;
        tree *root;
        root = (tree *)malloc(sizeof(tree));
        root=creat();
        inorder(root);
        printf("\n");
        postorder(root);
        printf("\n");
    }
    return 0;
}

猜你喜欢

转载自blog.csdn.net/rangran/article/details/81701001