给出以下权重2,3,4,7,9,18,25构造啥夫曼树,先序遍历输出节点的值,换行隔开+++++++++++++++参考答案++++++++++++++++++++关于参考答案的说明,放出答案来,并不是说这个题就要这样做,应该有更好的解法,这只是我课堂上随手写出来的,没有重构和优化,留给同学改进的空间。另外放答案出来目的是给写java代码困难的同学以基础语法上帮助,切不应以此参考代码顶替你的作业代码实现。学习通上传代码会滤过掉行前缩进,在eclipse下按ctrl+shift+f格式化一下。++++++++++++++++package greedy;import java.util.PriorityQueue;class HuffmanTree implements Comparable {String data;int weight;String code;HuffmanTree lchild;HuffmanTree rchild;public HuffmanTree(String data, int weight, HuffmanTree lchild, HuffmanTree rchild) {super();this.data = data;this.code="";this.weight = weight;this.lchild = lchild;this.rchild = rchild;}@Overridepublic int compareTo(HuffmanTree o) {// TODO Auto-generated method stubif (this.weight < o.weight) {return -1;}if (this.weight == o.weight) {return 0;}return 1;}}public class Huffman {// 有6个结点 a, b, c, d,e,f,权值分别为 2, 3, 7, 9,18,25,public static void main(String[] args) {PriorityQueue queue = new PriorityQueue();queue.add(new HuffmanTree("a", 2, null, null));queue.add(new HuffmanTree("b", 3, null, null));queue.add(new HuffmanTree("c", 7, null, null));queue.add(new HuffmanTree("d", 9, null, null));queue.add(new HuffmanTree("e", 18, null, null));queue.add(new HuffmanTree("f", 25, null, null));HuffmanTree root=null;while (!queue.isEmpty()) {HuffmanTree lchild = queue.poll();HuffmanTree rchild = queue.poll();if (rchild != null) {root = new HuffmanTree(null, lchild.weight + rchild.weight, lchild, rchild);queue.add(root);} else {root = lchild;}}preOrderVisit(root);}public static void preOrderVisit(HuffmanTree root) {if(root==null){return;}if(root.lchild==null && root.rchild==null){System.out.println(root.data+":"+root.code);}if(root.lchild!=null){root.lchild.code=root.code+"1";preOrderVisit(root.lchild);}if(root.rchild!=null){root.rchild.code=root.code+"0";preOrderVisit(root.rchild);}}}