江西师范大学数据结构树和二叉树编程作业(下)

1.二叉树的基本运算(30分)

#include <stdio.h>
#include <stdlib.h>
typedef struct node /*二叉树结构定义*/
{
   
    char data;
    struct node *lchild,*rchild;
} binnode;
typedef binnode *bintree;

bintree  CreateBinTree();/*按前序遍历顺序建立一棵二叉树,返回树根地址	*/
void PreOrder(bintree t);    /* t为指向树根结点的指针,树的前序遍历*/
void InOrder(bintree t); /* t为指向树根结点的指针,树的中序遍历*/
void PostOrder(bintree t); /* t为指向树根结点的指针,树的后序遍历*/
bintree PreLast(bintree t); /* t为指向树根结点的指针,返回先序遍历的最后一个结点地址,如果树为空,返回NULL*/
bintree PostFirst(bintree t);/* t为指向树根结点的指针,返回后序遍历的第一个结点地址,如果树为空,返回NULL*/
int main()
{
   
    bintree t,p;
    t=CreateBinTree();   /*建立二叉树t的存储结构*/
    printf("\nthe PreOrder is:");
    PreOrder(t);
    printf("\nthe InOrder is:");
    InOrder(t);
    printf("\nthe PostOrder is:");
    PostOrder(t);
    printf("\nthe PreLast is:");
    p=PreLast(t);
    if (p==NULL) printf("null");
    else printf("%c",p->data);
    printf("\nthe PostFirst is:");
    p=PostFirst(t);
    if (p==NULL) printf("null");
    else printf("%c",p->data);
    return 0;
}
bintree PostFirst(bintree t)
{
   
    if(t == NULL)
    {
   
        return NULL;
    }
    if(t->lchild)
        t = PostFirst(t->lchild);
    else if(t->rchild)
        t = PostFirst(t->rchild);
    else
        return t;
}
bintree PreLast(bintree t)
{
   
    if(t == NULL)
    {
   
        return NULL;
    }
    if(t->rchild)
        t =  PreLast(t->rchild);
    else if(t->lchild)
        t = PreLast(t->lchild);
    else
        return t;
}
void PostOrder(bintree t)
{
   
    bintree x = t;
    if(x)
    {
   
        PostOrder(x->lchild);
        PostOrder(x->rchild);
        printf("%c",x->data);
    }
}
void InOrder(bintree t)
{
   
    bintree x = t;
    if(x)
    {
   
        InOrder(x->lchild);
        printf("%c",x->data);
        InOrder(x->rchild);
    }
}
void PreOrder(bintree t)
{
   
    bintree x = t;
    if(x)
    {
   
        printf("%c",x->data);
        PreOrder(x->lchild);
        PreOrder(x->rchild);
    }
  • 6
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 3
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值