堆序树的集合,森林
二项树 Bk 由一个带有儿子 B1 B2 ... Bk-1 的根组成 ,高度为 k 的二项树恰好有 2^k 个节点
目标:用二项树的集合惟一表示任意大小的优先队列
树的合并只在乎有没有保持堆序性,兄弟节点间没有要求
编程就是要让自己像计算机思考,一次只考虑一个步骤
合并 2 个优先队列部分代码
T1=H1->TheTrees[i]; T2=H2->TheTrees[i]; switch (!!T1 + 2*!!T2 + 4*!!Carry) { case 0: case 1: break; case 2: H1->TheTrees[i] = T2; H2->TheTrees[i] = NULL; break; case 4: H1->TheTrees[i] = Carry; Carry = NULL; break; case 3: carry = CombineTrees(T1, T2); H1->TheTrees[i] = H2->TheTrees[i] = NULL; break; case 5: Carry = CombineTrees(T1, Carry); H1->TheTrees[i] = NULL; break; case 6: Carry = CombineTrees(T2, Carry); H2->TheTrees[i] = NULL; break; case 7: H1->TheTrees[i] = Carry; Carry = CombineTrees(T1, T2); H2->TheTrees[i] = NULL; break; }
CombineTrees代码如下
BinTree CombineTrees(BinTree T1, BinTree T2) { if (T1->Element > T2->Element) { return CombineTrees(T2, T1); } T2->NextSibling = T1->LeftChild; T1->LeftChild = T2; return T1; }