优先队列实现哈夫曼树-先序遍历&中序遍历&后序遍历

为使得哈夫曼树唯一,我们通常规定左子树的权值小于右子树

import java.util.*;
public class Build_huffman_tree {
    public static void main(String args[]){
      Scanner in=new Scanner(System.in);
      while(in.hasNext()){
          int n=in.nextInt();
          Queue<Integer> queue=new PriorityQueue<Integer>();  //优先队列构建哈夫曼树
          for(int i=0;i<n;i++)
              queue.offer(in.nextInt());
          Tree root[]=new Tree[2*n-1];
          int temp1=0,temp2=0,sum=0;
          int cnt=2*n-2;
          //每次从队列里取出最小的两个,构成一个新的节点
          while(queue.size()>1){
              temp1=queue.poll();
              temp2=queue.poll();
              sum+=temp1+temp2;
              root[cnt-1]=new Tree(temp1);
              root[cnt]=new Tree(temp2);
              cnt-=2;
              queue.offer(temp1+temp2);
          }
          root[0]=new Tree(queue.poll());
          System.out.println("最短路径和为:"+sum);
          //构建哈夫曼树
          for(int i=0;i<2*n-2;i+=2){
              root[i].left=root[i+1];
              root[i].right=root[i+2];
          }
          System.out.println("先序遍历");
          f_pre(root[0]);
          System.out.println("中序遍历");
          f_in(root[0]);
          System.out.println("后序遍历");
          f_post(root[0]);
          System.out.println("层次遍历");
          f_ceng(root[0]);
      }
    }
    //先序遍历
    public static void f_pre(Tree root){
        if(root!=null){
            System.out.println(root.value);
            f_pre(root.left);
            f_pre(root.right);
        }
    }
    //中序遍历
    public static void f_in(Tree root){
        if(root!=null){
            f_pre(root.left);
            System.out.println(root.value);
            f_pre(root.right);
        }
    }
    //后序遍历
    public static void f_post(Tree root){
        f_pre(root.left);
        f_pre(root.right);
        System.out.println(root.value);
    }
    //层次遍历
    public static void f_ceng(Tree root){
        if(root!=null){
            Queue<Tree> ans=new LinkedList<Tree>();
            ans.offer(root);
            while(ans.size()>0){
                Tree temp1=ans.poll();
                System.out.println(temp1.value);
                if(temp1.left!=null){
                    ans.offer(temp1.left);
                }
                if(temp1.right!=null){
                    ans.offer(temp1.right);
                }
            }
        }
    }
}
//定义数据结构
class Tree{
    Tree left;
    Tree right;
    int value;
    Tree(int value){
        this.value=value;
        this.left=null;
        this.right=null;
    }
}

猜你喜欢

转载自blog.csdn.net/anhuibozhoushatu/article/details/83817150
今日推荐