一,二叉树的算法
1,求节点个数
可以用遍历,遍历几个就是几个。另一种是递归,结点=左子树结点+右子树结点+1。
int count(BiNode * root){
int number=0;
if (root==NULL)
number=0;
else
number=count(root->lchild)+count(root->rchild)+1;
return number;
}
2,叶子结点数目
遍历到叶子节点数目加一。或者递归左子树叶加右子树叶
//遍历
void countleaf(BiNode * root){
if (root) {
if (root->lchild==NULL && root->rchild==NULL)
leafcount=leafcount+1;
else
{
countleaf(root->lchild);
countleaf(root->rchild);
}
}
return;
}
//递归
int leafcount(BiNode * 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;
}
3,树高
max(左子树高度,右子树高度)+1
int btree::shugao(bnode *bt){
int i=0;
if(bt==NULL) return 0;
else{
i=max(shugao(bt->lchild),shugao(bt->rchild))+1;
}
return i;
}
4,树的宽度
层次遍历可实现,运用队列
struct q_element{ BiNode*root int level;};
int BiTree::Width(){
queue< struct q_element > q;
int num[100]={0,1};
q_element s,child;
BiNode *root;
root=this->root;
if(root==NULL)
return 0;
s.root=root; s.level=1; q.push(s);
while(!q.empty()) {
s=q.front();
if(s.root->lchild){
num[s.level+1]++;
child.root=s.root->lchild;
child.level=s.level+1;
q.push(child);
}
if(s.root->rchild) {
num[s.level+1]++;
child.root=s.root->rchild;
child.level=s.level+1;
q.push(child);
}
q.pop();
}
int max=0,i=1;
while(num[i]>0){
if(max<num[i])
max=num[i];
i++;
}
return max;
}
二,二叉树的转换
树转二叉树:兄弟变儿子
森林转换为二叉树
⑴ 将森林中的每棵树转换成二叉树;
⑵ 从第二棵二叉树开始,
依次把后一棵二叉树的根结点作为前一棵二叉树根结点的右孩子,
当所有二叉树连起来后,此时所得到的二叉树就是由森林转换得到的树二叉树。
三,最优二叉树与哈夫曼编码
二叉树的带权路径长度:设二叉树具有n个带权值的叶子结点,从根结点到各个叶子结点的路径长度与相应叶子结点权值的乘积之和。wpl
哈夫曼树:只有度为0与度为2的结点
哈夫曼编码是前缀编码,保证解码时不会出现多种可能,是不等长编码,左0右1或左1右0
四,线索二叉树
线索:将二叉链表中的空指针域指向前驱结点和后继结点的指针被称为线索;
线索化:使二叉链表中结点的空链域存放其前驱或后继信息的过程称为线索化;
线索二叉树:加上线索的二叉树称为线索二叉树
struct ThrNode
{
T data;
ThrNode<T> *lchild, *rchild;
flag ltag, rtag; //标志表示是否孩子结点处存的是真孩子
};
函数设置形参root和全局变量pre,分别表示要处理的树的根结点和其前驱结点
如果root!=NULL
中序线索化root的左子树
中序线索化root本身
如果root->lchild==NULL
root->left=pre,root->ltag=1;
如果root->rchild==NULL,root->rtag=1,
如果pre!=NULL, 并且pre->rtag=1,
pre->rchild=root,;
pre=root
中序线索化root的右子树