哈夫曼树可执行代码(创建,层次遍历)

import java.util.LinkedList;
import java.util.Queue;
import java.util.Scanner;

import design.BTree.BTNode;


public class HuffMan<AnyType> {
    HNode root=new HNode();
	class HNode<AnyType>{
		double data;
		HNode left;
		HNode right;
		public HNode(double data){
			this.data=data;
		}
		public HNode(){}
	}
	//创建哈夫曼树
	public HNode creatTree(){
		Queue<Double> q=new LinkedList();
		Scanner sc=new Scanner(System.in);
	    System.out.println("请输入权的个数");
		int numble=sc.nextInt();
		HNode rootNode[]=new HNode[numble-1];   //存放每组的根
		int r=0;
		double w[]=new double[numble];
		System.out.println("请逐个输入权值,用空格隔开");
		for(int i=0;i<numble;i++){
			w[i]=sc.nextDouble();	
		}
		w=maopao(w);                     //对权值进行排序
		for(int i=0;i<w.length;i++){
			q.add(w[i]);
		}
		HNode node=new HNode();
		while(!q.isEmpty()){	
			double n1=q.remove();          //选出权值最小的两个
			double n2=q.remove();
			HNode node1=new HNode(n1);
			HNode node2=new HNode(n2);
		    HNode root=new HNode(n1+n2);    //得出根
			root.left=node1;
			root.right=node2;
			
			numble=numble-2; 
			if(numble>0){
			     q.add(n1+n2);
			     numble++;
			     double w2[]=new double[numble]; 
				 for(int i=0;i<numble;i++){           //新的权值
					w2[i]=q.remove();
				 }
				 w2=maopao(w2);                       //排序
				 for(int i=0;i<numble;i++){           //重新入队
				   q.add(w2[i]);
				 }
			}//if
		   rootNode[r]=root;     //将根存入数组
		   r++;
		}//while
		
		for(int i=0;i<rootNode.length;i++)
			for(int j=i+1;j<rootNode.length;j++){
				if(rootNode[i].data==rootNode[j].left.data){       //将所有结点连起来
					rootNode[j].left.left=rootNode[i].left;
					rootNode[j].left.right=rootNode[i].right;
					break;
				}
				if(rootNode[i].data==rootNode[j].right.data){       //将所有结点连起来
					rootNode[j].right.left=rootNode[i].left;
					rootNode[j].right.right=rootNode[i].right;
					break;
				}
				
			}
		
		return rootNode[rootNode.length-1];                        //返回最大的根
	}
	public double[] maopao(double b[]){
		double a[]=b.clone();
		for(int i=0;i<a.length-1;i++){
			for(int j=0;j<a.length-1-i;j++){
				if(a[j+1]<=a[j]){
					double temp=a[j];
					a[j]=a[j+1];
					a[j+1]=temp;
				}
			}
		}
		return a;
	}
	 //层次非递归遍历
		public void levelOrder(HNode root){
			int i=0;
			Queue<HNode> q=new LinkedList<HNode>();
			q.add(root);
			while(q.isEmpty()!=true){
				HNode step=q.remove();
				System.out.print(step.data+"   ");
				if(step.left!=null){
					q.add(step.left);
				}
				if(step.right!=null){
					q.add(step.right);
				}
			}
			System.out.println();
		}
		
	public static void main(String[] args) {
        HuffMan h=new HuffMan();
        h.root=h.creatTree();
        System.out.println("遍历"); 
        h.levelOrder(h.root);
       
	}

}

版权声明:本文为博主原创文章,未经博主允许不得转载。

原文地址:https://www.cnblogs.com/dingxiaoyue/p/4931846.html