1)
思想:
设置全局变量sum统计权值之和
①若该节点是叶子结点,则变量sum加上该节点深度和权值之积
②若该节点是非叶子结点,左子树不空则递归调用左子树,右子树不空递归调用右子树,深度为本结点深度+1
③最后输出sum值即可
//带权路径长度
int sum;
int WPL(Tree T,int deep){
if(T->left==NULL&&T->right==NULL)
{
sum+=deep*(T->weight); //为根结点则深度*权值
}
if(T->left!=NULL){ //左子树不为空左子树递归遍历
WPL(T->left,deep+1);
}
if(T->right!=NULL){//右子树不为空右子树递归遍历
WPL(T->right,deep+1);
}
return sum;
}
int WPL_sum(Tree T){
return WPL(T,0);
}
2)
typedef struct BiTNode{ int weight; struct BiTNode *left,*right; }TNode,*Tree;
3)
完整代码
#include<iostream> #include<stdlib.h> #include<bits/stdc++.h> #include<queue> #define ElemType int using namespace std; typedef struct BiTNode{ ElemType data; struct BiTNode *lchild,*rchild; }TNode,*Tree; int treenum[]={1,2,4,0,0,5,0,0,3,0,0}; int k; void createTree(Tree &T,int &k) { ElemType n; // printf("输入为0停止!\n"); // scanf("%d",&n); if(treenum[k]==0){ T=NULL; k++; } else{ T=new TNode; T->data=treenum[k]; k++; // cout<<"T="<<T->data<<"k="<<k<<endl; createTree(T->lchild,k); createTree(T->rchild,k); } } //带权路径长度 int sum; int WPL(Tree T,int deep){ if(T->lchild==NULL&&T->rchild==NULL) { sum+=deep*(T->data); //为根结点则深度*权值 } if(T->lchild!=NULL){ //左子树不为空左子树递归遍历 WPL(T->lchild,deep+1); } if(T->rchild!=NULL){//右子树不为空右子树递归遍历 WPL(T->rchild,deep+1); } return sum; } int WPL_sum(Tree T){ return WPL(T,0); } //先序遍历 int PreTree(Tree &T) { if(T==NULL){ return 0; } else{ cout<<T->data; PreTree(T->lchild); PreTree(T->rchild); } } int main() { Tree T; k=0; createTree(T,k); cout<<WPL_sum(T); return 0; }