王道C语言导学班 中级Day7作业
#define _CRT_SECURE_NO_WARNINGS
#include<stdlib.h>
#include<stdio.h>
typedef char Elemtype;
typedef struct BiNode {
Elemtype data;
struct BiNode* lchild;
struct BiNode* rchild;
}BiNode,*BiTree;
typedef struct tag {
BiTree p;
struct tag* pnext;
}tag_t,*ptag_t;
void preOrder(BiTree T) {//前序遍历
if (T != NULL) {
putchar(T->data);
preOrder(T->lchild);
preOrder(T->rchild);
}
}
int main() {
//层次建树
BiTree tree=NULL;//树
BiTree newtree = NULL;//保存输入数据的临时节点
ptag_t phead=NULL, ptail=NULL, pcur=NULL, listpnew;//队列
char a;
while (scanf("%c", &a) != EOF) {
if (a == '\n') {
break;
}
newtree = (BiTree)calloc(1, sizeof(BiNode));//新节点
newtree->data = a;
listpnew = (ptag_t)calloc(1, sizeof(tag_t));
listpnew->p = newtree;//把树的新节点地址放到队列里
if (tree == NULL) {
tree = newtree;//树为空时,把节点赋给树根
phead = listpnew;
ptail = listpnew;//队头队尾指向第一个节点
pcur = listpnew;
continue;//跳出循环
}
else {
ptail->pnext = listpnew;
ptail = listpnew;//加入队列里去
}
if (pcur->p->lchild == NULL) {
pcur->p->lchild = newtree;//左孩子为空,加入左孩子
}
else if (pcur->p->rchild == NULL) {
pcur->p->rchild = newtree;
pcur = pcur->pnext;//右孩子,节点满了,移动到下一个节点
}
}
preOrder(tree);
return 0;
}