解析:考察二叉树带权路径问题,二叉树的带权路径长度问题为每个叶结点的深度与权值之积的总和。
先序遍历的时候需要采用递归调用来进行二叉树的遍历,把每个结点的深度作为递归函数的一个参数进行传递.具体步骤如下:
若当前访问结点是叶结点,则总长度加上该结点的深度与权值之积
若该结点是非叶结点,若左子树不为空,递归调用左子树,若右子树不为空,递归调用右子树,直至最后返回总长度
typedef struct BiNode{
int weight;
struct BiTNode *lchild,rchild;
}BiNode,*BiTree;
int Weight(BiTree root,int deep){
static long wpl=0;
if(root->lchild==NULL && root->rchild==NULL){
wpl=wpl+deep*root->weight;
}
if(root->lchild !=NULL){
Weight(root->lchild,deep++);
}
if(root->rchild !=NULL){
Weight(root->rchild,deep++);
}
return wpl;
}