求二叉树结点的数目:
void Count(BiNode *root){
if (root) {
Count(root->lchild);
number+ +; //number为数据成员
Count(root->rchild);
}
}
树中结点的数目等于左子树结点的数目加上右子树结点的数目加1
template<class T>
int BiTree<T>::count(BiNode<T>* root){
int number=0;
if (root==NULL)
number=0;
else
number=count(root->lchild)+count(root->rchild)+1;
return number;
}
叶子节点的数目
增加一个leafcount的数据成员
template<typename T>
void BiTree<T>:: countleaf(BiTreeNode<T> * root){
if (root) {
if (root->lchild==NULL && root->rchild==NULL)
leafcount=leafcount+1;
else
{
countleaf(root->lchild);
countleaf(root->rchild);
}
}
return;
}
树中叶子节点的数目等于左子树中叶子节点的数目+右子树中叶子节点的数目。
template<class T>
int BiTree<T>::leafcount(BiNode<T>* root){
int number=0;
if (root= =NULL)
number=0;
else if(root->lchild= =NULL && root->rchild==NULL)
number=1;
else
number=leafcount(root->lchild)+leafcount(root->rchild);
return number;
}
树的高度
template<typename T>
int BiTree<T>::cal_height(BiTreeNode<T> * root){
int lheight=0,rheight=0;
if (root==0) return 0;
lheight=cal_height(root->lchild);
rheight=cal_height(root->rchild);
if (lheight>rheight) return lheight+1;
else return rheight+1;
}
树和二叉树之间的对应关系
1:兄弟加线
2:保留双亲与第一个孩子连线,删去与其他孩子的连线
3:顺时针转动,使之层次分明。
森林转化为二叉树
1:将森林中的每棵树转换成二叉树;
2:从第二棵二叉树开始,依次把后一棵二叉树的根结点作为前一棵二叉树根结点的右孩子,当所有二叉树连起来后,此时所得到的二叉树就是由森林转换得到的二叉树。
二叉树转化为树或森林
1:加线——若某结点x是其双亲y的左孩子,则把结点x的右孩子、右孩子的右孩子、……,都与结点y用线连起来;
2:去线——删去原二叉树中所有的双亲结点与右孩子结点的连线;
3: 层次调整——整理由⑴、⑵两步所得到的树或森林,使之层次分明。