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

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

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;
    }
}
  • 2
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值