二叉树的带权路径长度: 每个叶结点的深度与权值之积德总和。
方法:先序遍历或层次遍历
结点类型定义:
typedef struct BiTNode{
int weight;
struct BiTNode *lchild,*rchild;
}BiTNode,BiTree;
基于先序:
使用static 变量 wpl记录权值,每个结点的深度作为递归函数的参数传递。具体算法如下
1)若是叶结点,wpl=wpl+该结点的深度与权值之积;
2)非叶结点,若左子树不空,对左子树调用递归算法;
若右子树不空,对其调用递归算法,深度参数为本结点的深度参数加1;
3)最后返回wpl。
int WPL(BiTree root){
return wpl_PreOrder(root,0);
}
int wpl_PreOrder(BiTree root,int deep){
static wpl = 0;
if(root->llchild == NULL && root->rchild==NULL)
wpl+=deep*root->weight;
if(root->lchild!=NULL)
wpl_PreOrder(root->lchild,deep+1);
if(root->rchild!=NULL)
wpl_PreOrder(root->rchild,deep+1);
}
基于层次遍历:
使用队列进行层次遍历,记录当前的层数;
1)遍历到叶结点时,累计wpl;
2)非叶结点时,将其子树加入队列;
3)该结点为该层最后一个结点时,层数自增1;
4)队列空遍历结束,返回wpl;
#define Maxsize 100 //队列最大容量
int wpl_levelOrder(BiTree root){
BiTree q[Maxsize];
int end1,end2;
end1=end2=0;
int wpl=0,deep=0;
BiTree lastNode; //当前层最后一个结点
BiTree newLastNode; //下一层最后一个结点
lastNode = root;
newLastNode = NULL;
q[end2++]=root;
while(end1!=end2){
BiTree t=q[end1++];
if(t->lchild==NULL&&t->rchild==NULL)//叶结点统计wpl
wpl+=deep*t->weight;
if(t->lchild != NULL){
q[end2++]=t->lchild;//非叶结点入队
newLastNode=t->lchild;
}
if(t->rchild != NULL){
q[end2++]=t->rchild;
newLastNode=t->rchild;
}
if(t==lastNode){
lastNode=newLastNode;
deep+=1;
}
}
return wpl;
}