哈夫曼树

代码

#include 
#include 
#include 
using namespace std;

typedef struct node{
	struct node* lchild;
	struct node* rchild;
	int weight;
	node(int w,struct node* l,struct node* r){
		this->weight = w;
		this->lchild = l;
		this->rchild = r;
	}
}TreeNode;

struct cmp{
	bool operator()(TreeNode* node1,TreeNode* node2){
		return node1->weight > node2->weight;
	}
};


TreeNode* Create_HuffmanTree(int* weights,int size)
{
	priority_queue,cmp> q;
	for(int i = 0 ; i < size ; i++){
		TreeNode* node = new TreeNode(weights[i],NULL,NULL);
		q.push(node);
	}
	TreeNode* node1,*node2;
	while(q.size() != 1){
		node1 = q.top();
		q.pop();
		node2 = q.top();
		q.pop();
		TreeNode* node = new TreeNode(node1->weight+node2->weight,node1,node2);
		q.push(node);
	}
	TreeNode* root = q.top();
	q.pop();
	return root;
}

//先序遍历
void PreOrderTraversal(TreeNode* root)
{
	if(root == NULL){
		return;
	}
	cout<weight<<" ";
	PreOrderTraversal(root->lchild);
	PreOrderTraversal(root->rchild);
} 

//中序遍历
void InOrderTraversal(TreeNode* root)
{
	if(root == NULL){
		return;
	}
	InOrderTraversal(root->lchild);
	cout<weight<<" ";
	InOrderTraversal(root->rchild);
} 

//后序遍历
void PostOrderTraversal(TreeNode* root)
{
	if(root == NULL){
		return;
	}
	PostOrderTraversal(root->lchild);
	PostOrderTraversal(root->rchild);
	cout<weight<<" ";
} 

int main()
{
	//初始化 
	int n;
	int* weights; 
	cout<<"请输入树节点个数:"<>n;
	weights = new int[n];
	memset(weights,0,sizeof(weights[0])*n);
	cout<<"请输入树节点权重:"<>weights[i];
	}
	//构造哈夫曼树 
	TreeNode* root = Create_HuffmanTree(weights,n);
	//先序遍历哈夫曼树
	cout<<"哈夫曼树的先序遍历为:"<

截图

哈夫曼树_第1张图片

你可能感兴趣的:(#,数据结构)