您的位置:首页 > 理论基础 > 数据结构算法

数据结构实验之求二叉树后序遍历和层次遍历

2016-08-10 21:38 453 查看


这道题的算法思想:主要是根据题中所给出的先序遍历和后序遍历的结果来创建二叉树,我们可以利用分而治之的思想来创建它的左子树和右子树,后面的层次遍历和后序遍历则比较容易理解。

代码如下:

#include <stdio.h>

#include <malloc.h>

#include <string.h>

struct node{

    char data;

    struct node *lchild,*rchild;

};

struct node *Createtree(char *pre,char *in,int len){/*建立二叉树,中序遍历中根节点的

    左边全都是左子树的中序,右边全是右子树中序。然而每个子树的先序序列的第一个节点

    是子树的根,而且向后移动中序查找得到的左子树节点数便可分开得到左右子树。因此可以用递归分而治之*/

    struct node *root;//创建根节点;

    if(len<=0)

        return NULL;

    root=(struct node*)malloc(sizeof(struct node));

    root->data=*pre;//将先序的第一个结点指定为当前子树的根;

    char *p;

    for(p=in;p!=NULL;p++){

        if(*p==*pre)

            break;

    }

    int lon=p-in;//左子树结点的个数;

    root->lchild=Createtree(pre+1,in,lon);//创建左子树;

    root->rchild=Createtree(pre+lon+1,p+1,len-lon-1);//创建右子树;

    return root;

}

void Houxu(struct node *root){/*后序遍历函数*/

    if(root){

        Houxu(root->lchild);

        Houxu(root->rchild);

        printf("%c",root->data);

    }

}

void Cengci(struct node* root){/*层次遍历函数*/

    int in,out;

    in=0;

    out=0;

    struct node* q[100];/*利用结构体数组来存储每个数组*/

    q[in++]=root;

    while(in>out){

        if(q[out]){

            printf("%c",q[out]->data);

            q[in++]=q[out]->lchild;

            q[in++]=q[out]->rchild;

        }

        out++;

    }

}

int main(){

    int n,i;

    char a[100],b[100];

    scanf("%d",&n);

    while(n--){

        scanf("%s",a);

        scanf("%s",b);

        char *pre,*in;

        pre=a;

        in=b;

        int len=strlen(a);

        struct node *root=Createtree(pre,in,len);

        Houxu(root);

        printf("\n");

        Cengci(root);

        if(n>=1)

            printf("\n");

    }

    return 0;

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: