二叉树(1)

Time Limit:1000MS  Memory Limit:65536K
Total Submit:199 Accepted:83

Description

1、 按扩展的先序序列(即包括空结点)输入二叉树的各结点,建立二叉树,并输出其先序、中序和后序遍历序列。


如图所示的二叉树的扩展的先序序列为:ABD111C E11F11(1代表空结点)

Input

输入有多组例子,每组数组占一行;

Output

输出对应的结果,每组结果占三行。

Sample Input

ABD111CE11F11

Sample Output

ABDCEF
DBAECF
DBEFCA

#include<stdio.h>
#include<stdlib.h>
char str[1000];
int i;
typedef struct node
{
    char data;
    struct node *lchild,*rchild;
}Tnode,*Tree;
int m=sizeof(Tnode);
Tree newnode()//新节点建立
{
    Tree p;
    p=(Tree)malloc(m);
    p->lchild=NULL;
    p->rchild=NULL;
    return p;
}
void Creat(Tree p)
{
    Tree s,q;
    if(str[i]=='1')
    {
        p->data=NULL;
        return ;
    }
    else
    {
        p->data=str[i];
        s=newnode();
        p->lchild=s;
        i++;
        Creat(s);
    }
    q=newnode();
    p->rchild=q;
    i++;
    Creat(q);
}
void pre(Tree t)
{
    if(t!=NULL)
    {
        if(t->data!=NULL)
            printf("%c",t->data);
        pre(t->lchild);
        pre(t->rchild);
    }
}
void in(Tree t)
{
    if(t)
    {
        in(t->lchild);
        if(t->data!=NULL)
            printf("%c",t->data);
        in(t->rchild);
    }
}
void post(Tree t)
{
    if(t)
    {
        post(t->lchild);
        post(t->rchild);
        if(t->data!=NULL)
            printf("%c",t->data);
    }
}


int main()
{
    Tree t;
    while(gets(str))
    {
        i=0;
        t=newnode();
        Creat(t);
        pre(t);
        printf("\n");
        in(t);
        printf("\n");
        post(t);
        printf("\n");
    }
    return 0;
}

  

  

posted on 2011-07-22 17:54  world_ding  阅读(150)  评论(0编辑  收藏  举报