任务描述
二叉树的带权路径长度(WPL)是二叉树中所有叶结点的带权路径长度之和。给定一棵二叉树T, 采用二叉链表存储,结点结构为:left weight right,其中叶结点的weight域保存该结点的非负权值。设root为指向T的根结点的指针,请设计求T的WPL的算法。
编程要求
输入
多组数据,每组数据一行,为一个二叉树的先序序列(序列中元素为0时,表示该结点为空,每两个元素之间用空格隔开)。当输入只有一个0时,输入结束。
输出
每组数据输出一行,为该二叉树的WPL。
测试说明
平台会对你编写的代码进行测试:
测试输入:
1 1 0 0 1 0 0
1 2 1 0 0 0 0
0
预期输出:
2
2
C++代码:
304.h
#include<iostream>
using namespace std;
typedef struct BiTNode
{
int weight;
struct BiTNode *left,*right;
}BiTNode,*BiTree;
void CreateBiTree(BiTree &T)
{//先序建立二叉树
int ch;
cin>>ch;
if(ch==0) T=NULL;
else{
T=new BiTNode;
T->weight=ch ;
CreateBiTree(T->left);
CreateBiTree(T->right);
}
}
int WPL(BiTree &T,int d)
{//求二叉树T的带权路径长度
int wpl = 0;
if (T != NULL)
{
if (T->left == NULL && T->right == NULL)
wpl += d * T->weight;
wpl += WPL(T->left, d + 1);
wpl += WPL(T->right, d + 1);
}
return wpl;
}
主函数文件不可编辑:
#include<iostream>
#include "304.h"
using namespace std;
int main()
{
while(1)
{
BiTree T;
CreateBiTree(T);
if(!T) break;
int d=0; //调用时T指向二叉树的根结点,d为0
cout<<WPL(T,d)<<endl;
}
return 0;
}