设计性实验一 二叉树的遍历

4 篇文章 0 订阅
3 篇文章 0 订阅

一.实验任务:

二叉树的遍历:分别以顺序存储结构和二叉链表作存储结构,试编写前序、中序、后序及层次顺序遍历二叉树的算法。

 

二.实验任务的子任务:

本人设计以二叉链表作存储结构,编写前序、中序、后序及层次顺序遍历二叉树的算法

 

三.算法分析(如图):文字或流程图或画图说明都可

  1.假设输入的数据即为一个二叉链结构。

  2.再分别按前序,中序,后序及层次顺序遍历二叉树结构。

  3.最后按实验顺序将结果进行显示。

 

四.源代码:

#include <stdio.h>

#include<malloc.h>

#include<stdio.h>

#define M 10

 

typedefintDataType;/*元素的数据类型*/

typedefstructnode

{

    DataTypedata;

    structnode *lchild,*rchild;

}BitTNode,*BiTree;

 

intfront=0,rear=0;

BitTNode *que[10];

BitTNode *creat()

{

    BitTNode *t;

    DataTypex;

    scanf("%d",&x);

    if(x==0)

        t=NULL;

    else{

        t=(BitTNode *)malloc(sizeof(BitTNode));

        t->data=x;

        t->lchild=creat();

        t->rchild=creat();

    }

    return(t);

}/*creat*/

/* 前序遍历二叉树t */

voidpreorder(BiTreet)

{

    if(t!=NULL)

    {

        printf("%4d",t->data);

        preorder(t->lchild);

        preorder(t->rchild);

    }

}

/* 中序遍历二叉树t */

voidinorder(BiTreet)

{

    if(t!=NULL)

    {

        inorder(t->lchild);

        printf("%4d",t->data);

        inorder(t->rchild);

    }

}

/* 后序遍历二叉树t */

voidpostorder(BiTreet)

{

    if(t!=NULL)

    {

        postorder(t->lchild);

        postorder(t->rchild);

        printf("%4d",t->data);

    }

}

voidenqueue(BitTNode *t)

{

    if (front!=(rear+1)%M)

    {

        rear=(rear+1)%M;

        que[rear]=t;

    }

}/*enqueue*/

 

 

BitTNode * delqueue()

{

    if(front==rear)returnNULL;

    {

        front=(front+1)%M;

        return (que[front]);

    }

}/*delqueue*/

 

 

/* 按层次遍历二叉树t */

voidlevorder(BiTreet)

{

    BitTNode *p;

    if(t!=NULL)

    {

        enqueue(t);

        while (front!=rear)

        {

            p=delqueue();

            printf("%4d",p->data);

            if(p->lchild!=NULL) enqueue(p->lchild);

            if(p->rchild!=NULL) enqueue(p->rchild);

        }

    }

}/* levorder */

voidmain()

{

    BitTNode *root;

    root=creat();

    printf("\n按先序遍历次序生成的二叉树");

    printf("\n前序遍历二叉树");

    preorder(root);

    printf("\n中序遍历二叉树");

    inorder(root);

    printf("\n后序遍历二叉树");

    postorder(root);

    printf("\n层次顺序遍历二叉树");

    levorder(root);

}

运行结果:

 

 

 

 

 

 

实验结论:

    通过本实验我们可以进一步了解,二叉树的创建,前、后、中序遍历,以及二叉树的一些基本性质等操作。对递归调用有了更进一步的理解。

       

  • 1
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值