欢迎来到天天文库
浏览记录
ID:38649168
大小:22.00 KB
页数:5页
时间:2019-06-17
《二叉树广义表建树,层次遍历二叉树》由会员上传分享,免费在线阅读,更多相关内容在教育资源-天天文库。
1、二叉树广义表建树,层次遍历二叉树#include#include#include#defineMAXSIZE20#defineTRUE1#defineFALSE0typedefstructBiTNode{chardata;structBiTNode*lchild,*rchild;}BiTNode,*BiTree;typedefstructQueue{BiTreetreenode[MAXSIZE];intfront;intrear;}Queue;voidCreatree(BiTree*,char*);/*广义表形式建树*/void
2、CountLeafNumbers(BiTreeT,int*count);/*统计叶子节点的个数*/intLevelOurput(BiTree);/*层次遍历二叉树*/voidInitQueue(Queue*);intIsQueueEmpty(Queue*);intEnQueue(Queue*,BiTreeT);intOutQueue(Queue*,BiTree*T);intmain(){char*p;inti=0,count=0;BiTreeT=NULL;p=(char*)malloc(sizeof(char)*MAXSIZE);printf("输入的字符间请以空格隔开(0结束):")
3、;for(i=0;ifront=0;q
4、ueue->rear=0;}intIsQueueEmpty(Queue*queue){if(queue->front==queue->rear)returnTRUE;elsereturnFALSE;}intEnQueue(Queue*queue,BiTreeT){if(queue->rear>=MAXSIZE)returnFALSE;else{queue->rear=(queue->rear+1)%MAXSIZE;queue->treenode[queue->rear]=T;returnTRUE;}returnTRUE;}intOutQueue(Queue*queue,BiTree*T
5、){if(IsQueueEmpty(queue))returnFALSE;else{queue->front=(queue->front+1)%MAXSIZE;(*T)=queue->treenode[queue->front];returnTRUE;}returnTRUE;}voidCreatree(BiTree*b,char*str){BiTreestack[MAXSIZE],p=NULL;charch;inttop=-1,k,j=0;*b=NULL;ch=str[j];while(ch!='0'){switch(ch){case'(':/*为左节点*/{top++;stack[t
6、op]=p;k=1;}break;case')':{top--;}break;case',':/*为右节点*/{k=2;}break;default:{p=(BiTree)malloc(sizeof(BiTNode));p->data=ch;p->lchild=p->rchild=NULL;if(*b==NULL)*b=p;else{switch(k){case1:{stack[top]->lchild=p;}break;case2:{stack[top]->rchild=p;}break;}}}break;}j++;ch=str[j];}}voidCountLeafNumbers(B
7、iTreeT,int*count)/*统计叶子节点的个数*/{if(T){if((!T->lchild)&&(!T->rchild))(*count)++;CountLeafNumbers(T->lchild,count);CountLeafNumbers(T->rchild,count);}}intLevelOurput(BiTreeT)/*层次遍历二叉树*/{BiTreep;Queuequeue;InitQueue(&queue);if(!
此文档下载收益归作者所有