java实践源码--哈弗曼树
生活随笔
收集整理的這篇文章主要介紹了
java实践源码--哈弗曼树
小編覺得挺不錯(cuò)的,現(xiàn)在分享給大家,幫大家做個(gè)參考.
package huffmanTree;
import java.util.ArrayDeque;
import java.util.ArrayList;
import java.util.List;
import java.util.Queue; public class HuffmanTree {/** * 節(jié)點(diǎn)實(shí)體 */ public static class Node<T> { // 數(shù)據(jù) T data; // 權(quán)重 int power; Node<T> leftNode; Node<T> rightNode; public Node(T data, int power) { this.data = data; this.power = power; } @Override public String toString() { // TODO Auto-generated method stub return "[data:" + data + " power:" + power + "]"; } @SuppressWarnings("unchecked") public boolean compareTo(Node node) { if (this.power < node.power) { return true; } return false; } } /** * 將集合將序排序 * * @param <T> * @param <E> * * @param list */ public static void sort(List<Node> list) { for (int i = 0; i < list.size() - 1; i++) { for (int j = i + 1; j < list.size(); j++) { if (list.get(i).compareTo(list.get(j))) { // 交換數(shù)組中的元素位置 Node node = list.get(i); list.set(i, list.get(j)); list.set(j, node); } } } } /** * 創(chuàng)建哈夫曼樹 * * @param list * @return */ @SuppressWarnings("unchecked") public static Node createHuffmanTree(List<Node> list) { while (list.size() > 1) { sort(list); Node left = list.get(list.size() - 1); Node right = list.get(list.size() - 2); Node parent = new Node("父節(jié)點(diǎn)", left.power + right.power); parent.leftNode = left; parent.rightNode = right; list.remove(list.size() - 1); list.remove(list.size() - 1); list.add(parent); } return list.get(0); } public static List<Node> deepFirst(Node root) { List<Node> list = new ArrayList<Node>(); Queue<Node> queue = new ArrayDeque<Node>(); queue.add(root); while (!queue.isEmpty()) { list.add(queue.peek()); Node twoLinkNode = queue.poll(); if (twoLinkNode.leftNode != null) { queue.add(twoLinkNode.leftNode); } if (twoLinkNode.rightNode != null) { queue.add(twoLinkNode.rightNode); } } return list; } }
測(cè)試類
總結(jié)
以上是生活随笔為你收集整理的java实践源码--哈弗曼树的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: Google JAVA编程风格
- 下一篇: 自己动手写文件系统