欢迎来到天天文库
浏览记录
ID:20267366
大小:51.00 KB
页数:12页
时间:2018-10-11
《二叉树建立与遍历,叶子结点数目以及树深度求法,采用递归求解》由会员上传分享,免费在线阅读,更多相关内容在行业资料-天天文库。
1、是我个人写的,很简单的记录下来了,呵呵呵。我的百度空间:http://hi.baidu.com/heihei_shaweiwei/blog/item/eec5a3de6bb28c0462279805.html#includeusingnamespacestd;//定义树的结构typedefstruct_binTree{chardata;_binTree*lNode,*rNode;}binTree;//创建二叉树voidcreateT(binTree*&rootNode,binTree*tempNode)
2、{if(rootNode==NULL){rootNode=tempNode;return;}else{if(rootNode->data>tempNode->data){createT(rootNode->lNode,tempNode);}elseif(rootNode->datadata){createT(rootNode->rNode,tempNode);}}}//打印已创建的数voidprintT(binTree*rootNode){if(rootNode==NULL)return;else{p
3、rintT(rootNode->lNode);cout<data<<"";printT(rootNode->rNode);}}//先序遍历二叉树voidpreTraverse(binTree*rootNode){if(rootNode==NULL)return;else{cout<data<<"";printT(rootNode->lNode);printT(rootNode->rNode);}}//中序遍历二叉树voidmidTraverse(binTree*rootNode)
4、{if(rootNode==NULL)return;else{printT(rootNode->lNode);cout<data<<"";printT(rootNode->rNode);}}//后序遍历二叉树voidlastTraverse(binTree*rootNode){if(rootNode==NULL)return;else{printT(rootNode->lNode);printT(rootNode->rNode);cout<data<<"";}}//计算结点的总个
5、数intnodeTotal(binTree*rootNode){if(rootNode==NULL)return0;else{return1+nodeTotal(rootNode->lNode)+nodeTotal(rootNode->rNode);}}//计算二叉树的深度inttreeDepth(binTree*rootNode){if(rootNode==NULL)return-1;else{intlH=treeDepth(rootNode->lNode);intrH=treeDepth(rootNode->rNode
6、);if(lH>rH)returnlH+1;returnrH+1;}}//计算叶子结点的个数intleafTotal(binTree*rootNode){if(rootNode==NULL)return0;else{if(rootNode->lNode==NULL&&rootNode->rNode==NULL)return1;else{intlH=leafTotal(rootNode->lNode);intrH=leafTotal(rootNode->rNode);returnrH+lH;}}}intmain(){binT
7、ree*rootNode,*tNode;rootNode=NULL;tNode=NULL;charch;cout<<"按照下面给出的顺序进行输入构建二叉树:"<>ch;while(ch!='0'){tNode=newbinTree;tNode->data=ch;tNode->lNode=NULL;tNode->rNode=NULL;createT(rootNode,tNode);cin>>ch;}if(rootNode==NULL){cout<<"Treeis
8、NULL."<
此文档下载收益归作者所有