1. 程式人生 > 實用技巧 >用層序遍歷求二叉樹的wpl值

用層序遍歷求二叉樹的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。