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;
}