//程序有误,代码有详细注释。
//只能输入一次值
//没有输出结果
#include<stdio.h>
#include<stdlib.h>
#include<malloc.h>
int c = 0;
typedef struct CSTREE
{
char data;
struct CSTREE *firstchild,*nextchild;
}CSNode,*CSTree; //二叉链表存储结构
typedef struct Qnode
{
struct Qnode *next;
char data;
}QNode,*QueuePtr; //链队列存储结构
typedef struct
{
QueuePtr front;
QueuePtr rear;
}*LinkQueue; //链队列指针
void GetTreeNode(char ch,CSTree *p) // 创建一个结点,并把 ch 存入到其中,让 p 指向该结点并返回。
{
*p = (CSTree)malloc(sizeof(CSNode));
(*p)->data = ch;
}
void CreatQueue(LinkQueue *Q)
{
(*Q)->rear = (QueuePtr)malloc(sizeof(QNode));
c++; //引用全局变量 c,使 Q.fornt 始终指向队列头
(*Q)->rear->next = NULL;
if(c == 1) (*Q)->front = (*Q)->rear;
}
void EnQueue(LinkQueue *Q,CSTree *p)
{
(*Q)->front->data = (*p)->data; // p指向的值插入队列中。
}
void GetHead(LinkQueue Q,CSTree *s) //获取队列头的值
{
(*s)->data = Q->front->data;
}
void DeQueue(LinkQueue *Q) //删除队列头的值
{
LinkQueue q;
q->front = (*Q)->front->next;
free((*Q)->front); //释放空间
(*Q)->front = q->front;
}
void pre(CSTree *s,CSTree T)
{
if(T->data != (*s)->data) //用头指针寻找与 s->data 的值相等的结点。
{
pre(s,T->firstchild);
pre(s,T->nextchild);
}
*s = T;
}
void Creat(CSTree *T)
{
CSTree p,s,r;
LinkQueue Q;
char fa,ch;
for( scanf("%c %c",&fa,&ch) ; ch != ' ' ;scanf("%c %c",&fa,&ch) ) // fa、ch 为父子对
{
GetTreeNode(ch,&p); //p指向该节点
CreatQueue(&Q); //创建一个队列空结点
EnQueue(&Q,&p); //把 p指向的值存入队列中
if(fa == '#') s = *T = p; // T指向头节点,p用来寻找节点。
else
{
GetHead(Q,&s); //获取队列头的值
while(s->data != fa)//判断队列头的值是否与 父子对中的 fa 相等
{
DeQueue(&Q); //删除队列头的值
GetHead(Q,&s); //再次获取队列头的值
}
}
pre(&s,*T); //寻找与队列头的值相等的结点,并用 s 指向它
if(!(s->firstchild)) //如果 s结点的左孩子不空
{
s->firstchild = p; // p 指向的结点作为 s 的左孩子
r = p;
}
else
{
r->nextchild = p; // p 作为 r 的右孩子
r = p;
}
}
}
void Preorder(CSTree T) //前序遍历二叉树
{
if(T)
{
printf("%d ",T->data);
Preorder(T->firstchild);
Preorder(T->nextchild);
}
}
int main()
{
CSTree T = NULL;
printf("请输入父子对:\n");
Creat(&T);
printf("\n前序打印二叉树: ");
Preorder(T);
return 0;
}