思想:基於先序遍歷,用一個靜態變量保存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; }