思想:基于先序遍历,用一个静态变量保存WPL把每个节点的深度作为参数传递
若为叶子结点,WPL=该节点深度*权值,若非叶子节点则递归调用
代码:
typedef struct BTNode { int weight; struct BTNode *lchild,*rchild; }BTNode,*BTree; int WPL(BTree root) { return WPL_CORE(root,0); } int WPL_CORE(BTree root,int deep) { static wpl=0; if(root->lchild==NULL&&root->rchild==null) wpl+=deep*root->weight; if(root->lchild!=NULL) WPL_CORE(root->lchild,deep+1); if(root->rchild!=NULL) WPL_CORE(root->lchild,deep+1); return wpl; }