[Level 12: WPL calculation of binary tree] [Programming training - tree and binary tree] [Touge] [bjfu-304]

mission details

The weighted path length (WPL) of a binary tree is the sum of the weighted path lengths of all leaf nodes in the binary tree. Given a binary tree T, stored in a binary linked list, the node structure is: left weight right, where the weight field of the leaf node stores the non-negative weight of the node. Let root be a pointer pointing to the root node of T, and please design an algorithm for WPL of T.

programming requirements

Input
multiple sets of data, one line for each set of data, which is a preorder sequence of a binary tree (when the element in the sequence is 0, it means that the node is empty, and every two elements are separated by spaces). When the input has only one 0, the input ends.

Output
Output one line for each set of data, which is the WPL of the binary tree.

Test instruction

The platform will test the code you write:

Test input:

1 1 0 0 1 0 0
1 2 1 0 0 0 0
0

Expected output:

2
2

C++ code:

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;
}

The main function file is not editable:

#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;
}

Guess you like

Origin blog.csdn.net/Tommy_Nike/article/details/128043902