二叉树的WPL计算
描述
二叉树的带权路径长度(WPL)是二叉树中所有叶结点的带权路径长度之和。给定一棵二叉树T, 采用二叉链表存储,结点结构为:left weight right,其中叶结点的weight域保存该结点的非负权值。设root为指向T的根结点的指针,请设计求T的WPL的算法。
输入
多组数据,每组数据一行,为一个二叉树的先序序列(序列中元素为0时,表示该结点为空,每两个元素之间用空格隔开)。当输入只有一个0时,输入结束。
输出
每组数据输出一行,为该二叉树的WPL。
输入样例 1
1 1 0 0 1 0 0 1 2 1 0 0 0 0 0
输出样例 1
2 2
#include<iostream>
#include<string>
using namespace std;
typedef struct BiNode {
int weight;
struct BiNode* left, * right;
}BiNode,*BiTree;
int sum;
void Create(BiTree& t) {
int a;
cin >> a;
if (a == 0) {
t = NULL;
}else{
t = new BiNode;
t->weight = a;
Create(t->left);
Create(t->right);
}
}
int WPL(BiTree& 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 main() {
while(1) {
BiTree t1;
Create(t1);
if (!t1) { break; }
sum = 0;
cout << WPL(t1, 0) << endl;
}
}