Huffman tree structure basic java version

Foreword:

Huffman tree is the minimum spanning tree.

The construction process is as follows:

The Huffman tree is not unique, but the length of the weighted path must be the same.

As follows, four nodes with weights of 1, 5, 8, 4,

The construction process of the huffman tree is as follows:

In general, it can be boiled down to the following steps:

Assuming that there are n weights, the constructed Huffman tree has n leaf nodes. The n weights are respectively set as w1, w2,..., wn, and the construction rules of the Huffman tree are:

1. Consider w1, w2,..., wn as a forest with n trees (each tree has only one node); 
2. In the forest, select the two trees with the smallest root node weight to merge , As the left and right subtrees of a new tree, and the root node weight of the new tree is the sum of the root node weights of its left and right subtrees; 
3. Delete the selected two trees from the forest, and Add the new tree to the forest; 
4. Repeat steps (02) and (03) until there is only one tree left in the forest, which is the Huffman tree obtained.

Not much to say, the code is as follows:

package Huffman树;

import java.util.ArrayList;
import java.util.Collections;
import java.util.Scanner;

public class Huffman {

	static class node implements Comparable<node>{//自排序

		int weight;//权值
		node lchild;
		node rchild;
		public node(int w,node l,node r)
		{
			this.weight=w;
			this.lchild=l;
			this.rchild=r;
		}
		
		public int compareTo(node o) {
			return this.weight-o.weight;
		}
	}
	
	
	static node createHuffmanTree(ArrayList<node> nodes)
	{
		while(nodes.size()>1)
		{
			Collections.sort(nodes);//排序
			
			node l=nodes.get(0);
			node r=nodes.get(1);
			//System.out.println(l.weight+" "+r.weight);
			node p=new node(l.weight+r.weight,l,r);
		
			//移走两个最小的
			nodes.remove(0);
			nodes.remove(0);
			//把大的放进去
			nodes.add(p);
		}
		return nodes.get(0);
	}
	
	//前序遍历,并求WPL 带权路径长度
	static long WPL=0;
	static void preorder(node root,int levelNum)
	{
		if(root.lchild==null)
		{
			WPL+=root.weight*levelNum;
			return;
		}
		else
		{
			preorder(root.lchild,levelNum+1);
			preorder(root.rchild,levelNum+1);
		}
		
	}
	
	public static void main(String[] args) {	
		ArrayList<node> nodes=new ArrayList<node>();
		Scanner cin=new Scanner(System.in);
		int n=cin.nextInt();
		for(int i=0;i<n;i++)
		{
			int w=cin.nextInt();//这里我直接把它的权值当做name了
			nodes.add(new node(w,null,null));
		}
		node r=createHuffmanTree(nodes);
		
		WPL=0;//WPL:带权路径长度
		preorder(r,0);
		System.out.println("WPL: "+WPL);
		cin.close();
	}

}

result:

Guess you like

Origin blog.csdn.net/Look_star/article/details/90210312