关于二叉树的其他算法以及树二叉树森林的转化

求二叉树结点的数目:

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: 层次调整——整理由⑴、⑵两步所得到的树或森林,使之层次分明。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值