开发者社区> 问答> 正文

数据结构试验(用C语言)建立一棵二叉树,并用递归或者非递归的算法分别用先序。中序和后序遍历、谢谢

能附一点实验思路更好

展开
收起
知与谁同 2018-07-18 09:33:39 2829 0
1 条回答
写回答
取消 提交回答
  • 12535
    #define LEN sizeof(struct tree)
    #define NULL 0
    #include<stdio.h>
    #include<malloc.h>
    struct tree
    {
    char data;
    struct tree *lchild,*rchild;
    };
    //创建二叉树
    struct tree *creat()
    {
    char c;
    struct tree *t;
    c=getchar();
    if(c==' ')
    t=NULL;
    else
    {
    t=(struct tree*)malloc(LEN);
    t->data=c;
    t->lchild=creat();
    t->rchild=creat();
    }
    return t;
    }
    //前序遍历
    void Preprint(struct tree*t)
    {
    if(t!=NULL)
    {
    printf("%c->",t->data);
    Preprint(t->lchild);
    Preprint(t->rchild);
    }
    }
    //中序遍历
    void Inprint(struct tree*t)
    {
    if(t!=NULL)
    {
    Inprint(t->lchild);
    printf("%c->",t->data);
    Inprint(t->rchild);
    }
    }
    //后序遍历
    void Postprint(struct tree*t)
    {
    if(t!=NULL)
    {
    Postprint(t->lchild);
    Postprint(t->rchild);
    printf("%c->",t->data);
    }
    }
    main()
    {
    struct tree *t;
    printf("Please input tree in order:\n");
    t=creat();
    printf("The result of Preorder traversal is\n");
    Preprint(t);
    printf("^\nThe result of Inorder traversal is\n");
    Inprint(t);
    printf("^\nThe result of Postorder traversal is\n");
    Postprint(t);
    printf("^\n");
    getch();
    }
    2019-07-17 22:55:11
    赞同 展开评论 打赏
问答排行榜
最热
最新

相关电子书

更多
“大数据+算法”助力B2B未来商业 立即下载
数据+算法定义新世界 立即下载
Apache Flink 流式应用中状态的数据结构定义升级 立即下载