用层序遍历求二叉树的wpl值

wpl指的是树的带权路径长度,是所有叶节点的权值乘以叶节点的深度之和,WPL=∑(叶节点的权值)*(叶节点的深度)

#include<iostream>
using namespace std;
const int MAXSIZE=0x0000ffff;
struct BiTree{
    int weight;
    BiTree*lchild,*rchild;
};
struct QueueNode{//队列节点,记录节点以及该节点的深度
    BiTree*p;
    int deep;
};
int get_wpl(BiTree*root){
    int wpl=0;
    int front,rear;//队列的队头和队尾指针
    front=rear=0;
    QueueNode queue[MAXSIZE];
    queue[rear].p=root;
    queue[rear].deep=1;
    rear++;
    //将root节点入队
    while(rear!=front)//队不空
    {
        BiTree* bt=queue[front].p;
        //从队头出队
        int deep=queue[front].deep;
        front++;  
        if(bt->lchild==NULL&&bt->rchild==NULL){
            wpl+=bt->weight*deep;//叶节点记录其带权路径
        }
        if(bt->lchild!=NULL){//左孩子入队
            queue[rear].p=bt->lchild;
            queue[rear].deep=deep+1;//左孩子的深度一定是双亲节点深度+1;
            rear++;
        }
        if(bt->rchild!=NULL){//右孩子入队
            queue[rear].p=bt->rchild;
            queue[rear].deep=deep+1;
            rear++;
        }
    }
    return wpl;
}

至于递归求解方法就是普通的DFS。

原文地址:https://www.cnblogs.com/kalicener/p/13452140.html