已知某哈夫曼树采用二叉链表存储,结点构造为
lchild | data | rchild |
其中,叶结点的data域中已经存放了该叶结点对应的权值。请写一非递归算法,该算法的功能是计算根结点指针为T的哈夫曼树的带权路径长度(WPL)。
要求:
1. 用文字简要给出算法的基本思想。
2. 根据算法的基本思想写出相应算法。
typedef struct HTree
{
struct HTree *lchild;
struct HTree *rchild;
int data;
}HTree;
int countWPL(HTree *ht)
{
if(ht != NULL)
{
HTree Stack[maxSize];
HTree *p = ht;
HTree *t;
//level表高度
int top = -1, level = 0, wpl = 0;
Stack[++top] = p;
level++;
while(top != -1)
{
t = Stack[--top];
level--;
if (t->lchild != NULL && t->rchild != NULL)
wpl += (t->data * level);
if (ht->rchild != NULL)
Stack[++top] = t->rchild;
if (ht->lchild != NULL)
Stack[++top] = t->lchild;
level++;
}
return wpl;
}
return -1;
}