Example #1
0
	void CreateHuffmanTree(const T* array, size_t size, const T& invalid)
	{	
		struct Compare 
		{
			bool operator()(HuffmanNode_P<T>*& lhs, HuffmanNode_P<T>*& rhs)
			{
				return lhs->_weight < rhs->_weight;
			}
		};

		// 1.将所有值构建为节点放入到一个最小堆中,Compare仿函数做比较器
		Heap<HuffmanNode_P<T>*, Compare> minHeap;
		for (int i = 0; i < size; ++i)
		{
			if (array[i] != invalid)
			{
				HuffmanNode_P<T>* node = new HuffmanNode_P<T>(array[i]);
				minHeap.Insert(node);
			}
		}

		if (minHeap.Empty())
			return;

		// 2.获取出最小和次小的节点做孩子节点,并构建这两个孩子节点的父节点进行链接。
		HuffmanNode_P<T>* parent = minHeap.GetHeapTop();
		while (minHeap.Size() > 1)
		{
			HuffmanNode_P<T>* first = minHeap.GetHeapTop();
			minHeap.Remove();
			HuffmanNode_P<T>* second = minHeap.GetHeapTop();
			minHeap.Remove();

			parent = new HuffmanNode_P<T>(first->_weight + second->_weight);
			parent->_left = first;
			parent->_right = second;
			first->_parent = parent;
			second->_parent = parent;

			minHeap.Insert(parent);
		}

		_root = parent;
	}
Example #2
0
	void CreateHuffmanTree(const T* array, size_t size)
	{
		struct Compare 
		{
			bool operator()(const HuffmanNode_A<T>* lhs, const HuffmanNode_A<T>* rhs)
			{
				return lhs->_weight < rhs->_weight;
			}
		};

		// 将节点的指针放入最小堆中,重写比较器
		_vNodes.reserve(size*2 - 1);
		Heap<HuffmanNode_A<T>*, Compare> minHeap;
		size_t index = 0;
		for (; index < size; ++index)
		{
			_vNodes.push_back(HuffmanNode_A<T>(array[index]));
			HuffmanNode_A<T>& node = _vNodes.back();
			node._index = index;
			minHeap.Insert(&node);
		}

		while (minHeap.Size() > 1)
		{
			HuffmanNode_A<T>* first = minHeap.GetHeapTop();
			minHeap.Remove();
			HuffmanNode_A<T>* second = minHeap.GetHeapTop();
			minHeap.Remove();

			_vNodes.push_back(HuffmanNode_A<T>(first->_weight + second->_weight));
			HuffmanNode_A<T>& parent = _vNodes.back();
			parent._index = index++;
			minHeap.Insert(&parent);

			first->_parent = parent._index;
			second->_parent = parent._index;
			parent._left = first->_index;
			parent._right = second->_index;
		}

		_rootIndex = minHeap.GetHeapTop()->_index;
	}