p127-19
typedef struct BiTNode {
int weight;
struct BiTNode *left, *right;
} BiTNode, *BiTree;
int GetWPL(BiTree root) {
BiTree Q[100], p = root;
int front = -1, rear = -1, layer = 0, r = 0, wpl = 0;
Q[++rear] = p;
while (front != rear) {
p = Q[++front];
if (!p->left && !p->right) { wpl += layer * p->weight; }
if (p->left) { Q[++rear] = p->left; }
if (p->right) { Q[++rear] = p->right; }
if (front == r) {
layer++;
r = rear;
}
}
return wpl;
}
int wpl_PreOrder(BiTree root, int deep) {
static int wpl = 0;
if (!root->left && !root->right) {
wpl += deep * root->weight;
}
if (root->left) {
wpl_PreOrder(root->left, deep + 1);
}
if (root->right) {
wpl_PreOrder(root->right, deep + 1);
}
return wpl;
}
int WPL(BiTree root) {
return wpl_PreOrder(root, 0);
}