【数据结构】如何建立先序二叉树

题目
1.考虑直接输入建立二叉树发现无法判定何时输入结束放弃
2.查看大佬代码发现大佬使用队列本来不准备用准备数组直接上发现似乎这样子不能一次性直接建立一个完整的二叉树,大佬果然是大佬
3.改C用C++引用太好用了我要去C++

#include <cstdio>
#include <cstdlib>
#include <cstring>
#define Max 100
typedef char elemType;
typedef struct tree{
    elemType data;
    struct tree *lc,*rc;
}Tree,*treeNode;

typedef struct queue{
    elemType data;
    struct queue *next;
}Queue;

typedef struct link{
    Queue *front;
    Queue *rear;
}LinkQueue;
void creatQueue(LinkQueue *q)
{
    q->rear =(Queue *)malloc(sizeof(Queue));
    q->front=q->rear;
    q->front->next=NULL;
}
void enQueue(LinkQueue *q,elemType ch)
{
    Queue* newQueue=(Queue *)malloc(sizeof(Queue));
    if(newQueue!=NULL)
    {
        newQueue->data=ch;
        newQueue->next=NULL;
        q->rear->next=newQueue;
        q->rear=newQueue;
    }
    else exit(0);

}
elemType outQueue(LinkQueue &q)
{
    if(q.front==q.rear)
        return '\0';
    Queue *tmp=q.front->next;
    elemType c=tmp->data;
    q.front->next=tmp->next;
    free(tmp);
    return c;
}//出队
void preOrderIn(LinkQueue &q,treeNode &root)
{
    elemType ch = outQueue(q);
    if(ch=='*'||ch=='\0')
        return;
    else root=(treeNode)malloc(sizeof(Tree));
    root->data=ch;
    root->lc=NULL;
    root->rc=NULL;
    preOrderIn(q,root->lc);
    preOrderIn(q, root->rc);
    return;
}
void preOrderOut(treeNode root)
{
    printf("%c",root->data);
    if(root->lc)
        preOrderOut(root->lc);
    if(root->rc)
        preOrderOut(root->rc);
}
void midOrderOut(treeNode root)
{
    if(root->lc)
        midOrderOut(root->lc);
    printf("%c",root->data);
    if(root->rc)
        midOrderOut(root->rc);
}
void afterOrderOut(treeNode root)
{
    if(root->lc)
        afterOrderOut(root->lc);
    if(root->rc)
        afterOrderOut(root->rc);
    printf("%c",root->data);
}
int main()
{
    elemType ch[Max];
    scanf("%s",ch);
    LinkQueue q;
    treeNode root;
    creatQueue(&q);
    for(int i = 0;ch[i]!='\0';i++)
        enQueue(&q,ch[i]);//将字符入队
    preOrderIn(q,root);
    preOrderOut(root);
    printf("\n");
    midOrderOut(root);
    printf("\n");
    afterOrderOut(root);
    printf("\n");
    return 0;


}


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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值