Create&TraverseBiTree
程序已就绪,可直接编译运行
#include
#define OK 1 #define TRUE 1 #define ERROR 0 #define FALSE 0 #define OVERFLOW -1
#define STACK_INIT_SIZE 200; #define STACKINCERMENT 20;
typedef int status; typedef char TElemType;
//-----二叉树的二叉链表存储表示----- typedef struct BiTNode {
TElemType data;
struct BiTNode *lchild,*rchild;//左右孩子指针 }BiTNode,*BiTree;//*BiTree表示指向该结构体的指针
//-----单链队列-----队列的链式存储结构
typedef BiTreeQElemType; typedef struct QNode {
QElemType data; struct QNode *next; }QNode,*QueuePtr;
typedef struct {
QueuePtr front; QueuePtr rear; }LinkQueue;
//------队列基本操作------
status InitQueue(LinkQueue&Q)
{//构造一个空队列Q
Q.front=(QueuePtr)malloc(sizeof(QNode)); Q.rear=Q.front;
if(!Q.front)exit(OVERFLOW); Q.front->next=NULL; return OK; }//InitQueue
status EnQueue(LinkQueue&Q,QElemType e) {//插入元素e为Q的新队尾元素 QueuePtr p;
p=(QueuePtr)malloc(sizeof(QNode)); if(!p)exit(OVERFLOW); p->data=e; p->next=NULL; Q.rear->next=p; Q.rear=p; return OK; }//EnQueue
status DeQueue(LinkQueue&Q,QElemType&e)
{//若队列不空,则删除Q的队头元素,用e返回其值,并返回OK
//否则返回ERROR QueuePtr p;
if(Q.front==Q.rear)return ERROR; p=Q.front->next; e=p->data; Q.front->next=p->next;
if(Q.rear==p)Q.rear=Q.front; free(p); return OK; }//DeQueue
status QueueEmpty(LinkQueue&Q) { intlen;
len=Q.rear-Q.front; if(len==0)return OK; return ERROR; }//QueueEmpty
status DestroyQueue(LinkQueue&Q) {//销毁队列Q while(Q.front)
{
Q.rear=Q.front->next; free(Q.front); Q.front=Q.rear; }
return OK; }//DestroyQueue
//-----二叉树的基本操作函数----- status CreateBiTree(BiTree&T)
//按先序次序输入二叉树中结点的值(一个字符),空格字符表示空树 //构造二叉链表表示的二叉树T {
char ch; scanf(\if(ch==' ')T=NULL; else {
if(!(T=(BiTNode*)malloc(sizeof(BiTNode))))exit(OVERFLOW); T->data=ch; //生成根节点 CreateBiTree(T->lchild); //构造左子树 CreateBiTree(T->rchild); //构造右子树