欢迎来到天天文库
浏览记录
ID:16275631
大小:28.50 KB
页数:3页
时间:2018-08-08
《数据结构二叉树遍历有关算法》由会员上传分享,免费在线阅读,更多相关内容在行业资料-天天文库。
1、//------------------二叉树结点的数据结构---------------typedefstructBiTNode//树节点定义{intvalue;BiTNode*lchild,*rchild;}BiTNode,*BiTree;//-------------------二叉树的遍历------------------voidPreorder(BiTreeroot)//先序遍历以T树根指针的二叉树(递归算法){if(root){cout<value;Preorder(root->lchild);Preorder(root->rchild);}}//--------
2、-----------先序遍历求二叉树的深度------------------intdepth=0,h=0;voidBiTreeDepthPre(BiTreeroot,inth,int&depth){if(root){if(h>depth)depth=h;BiTreeDepthPre(root->lchild,h+1,depth);BiTreeDepthPre(root->rchild,h+1,depth);}}//-------------------后序遍历求二叉树的深度------------------intBiTreeDepthPost(BiTreeroot){inthl=0,h
3、r=0;if(!root)return0;else{hl=BiTreeDepthPost(root->lchild);hr=BiTreeDepthPost(root->rchild);if(hl>=hr)returnhl+1;elsereturnhr+1;}}//-------------------二叉树的叶子节点数------------------intLeavesCount=0,noLeavesCount=0;voidCountLeaves(BiTreeroot)//计算叶子、非叶子数{if(root){if(!root->lchild&&!root->rchild)LeavesCo
4、unt++;elsenoLeavesCount++;CountLeaves(root->lchild);CountLeaves(root->rchild);}}//-------------------二叉树的节点最大值------------------intmaxvalue=-10000;voidFind_max_value(BiTreeroot){if(root){if(root->value>maxvalue)maxvalue=root->value;Find_max_value(root->lchild);Find_max_value(root->rchild);}}//-----
5、--------------交换二叉树的左右子树------------------voidchange(BiTree&root)//交换以T树根的二叉树的左右子树(递归算法){if(root){change(root->lchild);change(root->rchild);BiTNode*temp;temp=newBiTNode;temp->lchild=root->lchild;root->lchild=root->rchild;root->rchild=temp->lchild;deletetemp;}}
此文档下载收益归作者所有