资源描述:
《实现二叉树各种基本运算源程序》由会员上传分享,免费在线阅读,更多相关内容在应用文档-天天文库。
1、//BiTree.cpp:Definestheentrypointfortheconsoleapplication.//#include"stdafx.h"#include#include#defineMaxSize100typedefcharElemType;typedefstructnode{ElemTypedata;structnode*lchild;structnode*rchild;}BTNode;voidCreateBTNode(BTNode*&b,char*str);BTNode*FindNode(BTNod
2、e*b,ElemTypex);BTNode*LchildNode(BTNode*p);BTNode*RchildNode(BTNode*p);intBTNodeDepth(BTNode*b);voidDispBTNode(BTNode*b);intBTWidth(BTNode*b);intNodes(BTNode*b);intLeafNodes(BTNode*b);voidCreateBTNode(BTNode*&b,char*str){BTNode*St[MaxSize],*p=NULL;inttop=-1,k,j=0;charch;b=NULL;ch=st
3、r[j];while(ch!=' '){switch(ch){case'(':top++;St[top]=p;k=1;break;case')':top--;break;case',':k=2;break;default:p=(BTNode*)malloc(sizeof(BTNode));p->data=ch;p->lchild=p->rchild=NULL;if(b==NULL)b=p;else{switch(k){case1:St[top]->lchild=p;break;case2:St[top]->rchild=p;break;}}}j++;ch=s
4、tr[j];}}BTNode*FindNode(BTNode*b,ElemTypex)//返回data域为x的结点指针{BTNode*p;if(b==NULL)returnNULL;elseif(b->data==x)returnb;else{p=FindNode(b->lchild,x);if(p!=NULL)returnp;elsereturnFindNode(b->rchild,x);}}BTNode*LchildNode(BTNode*p)//返回*p结点的左孩子结点指针{returnp->lchild;}BTNode*RchildNode(BTNod
5、e*p)//返回*p结点的右孩子结点指针{returnp->rchild;}intBTNodeDepth(BTNode*b)//求二叉树b的深度{intlchilddep,rchilddep;if(b==NULL)return(0);else{lchilddep=BTNodeDepth(b->lchild);//左子数的高度rchilddep=BTNodeDepth(b->rchild);//右子树的高度return(lchilddep>rchilddep)?(lchilddep+1):(rchilddep+1);}}voidDispBTNode(BTNode
6、*b)//广义表输出二叉树{if(b!=NULL){printf("%c",b->data);if(b->lchild!=NULL
7、
8、b->rchild!=NULL){printf("(");DispBTNode(b->lchild);if(b->rchild!=NULL)printf(",");DispBTNode(b->rchild);printf(")");}}}intBTWidth(BTNode*b)//求二叉树宽度{struct{intlno;//结点的层次编号BTNode*p;//结点指针}Qu[MaxSize];//定义顺序非循环队列intfro
9、nt,rear;//定义队首和队尾指针intlnum,max,i,n;front=rear=0;//置队列为空if(b!=NULL){rear++;Qu[rear].p=b;//根结点指针入队Qu[rear].lno=1;//根结点的层次编号为1while(rear!=front)//队列不为空{front++;b=Qu[front].p;//队头出队lnum=Qu[front].lno;if(b->lchild!=NULL)//左孩子入队{rear++;Qu[rear].p=b->lchild;Qu[rear].lno=lnum+1;}if(b->rchil
10、d!=NULL)//右孩子入队{rea