二叉树的遍历(先序遍历、层序遍历、中序遍历、后序遍历)

Problem Description

已知一个按先序输入的字符序列,如abd,,eg,,,cf,,,(其中,表示空结点)。请建立二叉树并求二叉树的先序遍历、中序遍历、后序遍历、层次遍历序列。

Input

 输入数据有多行,第一行是一个整数t (t<1000),代表有t行测试数据。每行是一个长度小于50个字符的字符串。

Output

 输出二叉树的层次遍历序列。

Sample Input

2
abd,,eg,,,cf,,,
xnl,,i,,u,,

代码如下:

#include<stdio.h>
#include<stdlib.h>
#include<string.h>
struct node
{
    char data;
    struct node *lc,*rc;
};
int c;
char a[200];
struct node* creattree()//建立二叉树
{
    char x;
    x=a[c++];
    if(x==',')return NULL;
    struct node *root;
    root=(struct node*)malloc(sizeof(struct node));
    root->data=x;
    root->lc=creattree();
    root->rc=creattree();
    return root ;
};
void xian(struct node*root)
{
    if(root)
    {
        printf("%c",root->data);
        xian(root->lc);
        xian(root->rc);
    }
    return;
}
void zhong(struct node*root)
{
    if(root)
    {
        zhong(root->lc);
        printf("%c",root->data);
        zhong(root->rc);
    }
    return;
}
void hou(struct node*root)
{
    if(root)
    {
        hou(root->lc);
        hou(root->rc);
        printf("%c",root->data);
    }
    return;
}
void ceng(struct node *root)
{
        struct node *que[100];
        int i=0,j=0;
        que[j++]=root;
        while(i<j)
        {
            if(que[i])
            {
                que[j++]=que[i]->lc;
                que[j++]=que[i]->rc;
                printf("%c",que[i]->data);
            }
            i++;
        }
}
int main()
{
    int t;
    scanf("%d",&t);
    while(t--)
    {
        c=0;
        struct node *root;
        root=(struct node *)malloc(sizeof(struct node));
        scanf("%s",a);
        root=creattree();
        printf("层序遍历为:");
        ceng(root);
        printf("\n");
        printf("先序遍历为:");
        xian(root);
        printf("\n");
        printf("中序遍历为:");
        zhong(root);
        printf("\n");
        printf("后序遍历为:");
        hou(root);
        printf("\n");
    }
    return 0;
}
 

猜你喜欢

转载自blog.csdn.net/problemlife/article/details/81407516