二叉树的输入,遍历

适用二叉链表存储二叉树,实现二叉树的输入,先序遍历,中序遍历,后序遍历的递归算法,编制main程序调用这些子程序,并输出各遍历结果。

#include<stdio.h>
#include<malloc.h>

typedef int ElemType;
typedef struct Node
{
    struct Node *lchild;
    ElemType data;
    struct Node *rchild; 
    /* data */
}Tree;


Tree * create_tree(Tree *t){
//先序创建
    ElemType ch;
    scanf("%d",&ch);
    if(ch == 0)
        //t = (Tree *)malloc(sizeof(Tree))
        t = NULL;
    else{
        t = (Tree *)malloc(sizeof(Tree));
        t->data = ch;
        t->lchild = create_tree(t->lchild);
        t->rchild = create_tree(t->rchild);
    }
    return t;
}


void prior_show(Tree *t){
    if(t == NULL){
        //printf("THE TREE IS EMPTY\n");
        return ;
    }else{
        printf("%2d",t->data);
        prior_show(t->lchild);
        prior_show(t->rchild);
    }
}

void inorder_show(Tree *t){
    if(t == NULL){
        //printf("THE TREE IS EMPTY\n");
        return ;
    }else{
        inorder_show(t->lchild);
        printf("%2d",t->data);
        inorder_show(t->rchild);
    }
}

void last_show(Tree *t){
    if(t == NULL){
        //printf("THE TREE IS EMPTY\n");
        return ;
    }else{
        last_show(t->lchild);
        last_show(t->rchild);
        printf("%2d",t->data);
    }
}

void show(Tree *t, void (* order)(Tree *)){
    order(t);
    printf("\n");
}

int main(){
    Tree *t;
    t = create_tree(t);
    printf("先序:");
    show(t,prior_show);

    printf("中序:");
    show(t,inorder_show);

    printf("后序:");
    show(t,last_show);
    return 0;
}

  • 1
    点赞
  • 8
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值