import java.util.*; class HuffmanNode implements Comparable<HuffmanNode> { int frequency; char data; HuffmanNode left, right; public HuffmanNode(int frequency, char data) { this.frequency = frequency; this.data = data; } public boolean isLeaf() { return left == null && right == null; } @Override public int compareTo(HuffmanNode node) { return frequency - node.frequency; } } public class HuffmanCoding { public static void main(String[] args) { String text = "Hello, world!"; Map<Character, Integer> frequencyMap = buildFrequencyMap(text); HuffmanNode root = buildHuffmanTree(frequencyMap); Map<Character, String> huffmanCodes = buildHuffmanCodes(root); System.out.println("Original text: " + text); System.out.println("Huffman codes: " + huffmanCodes); System.out.println("Encoded text: " + encode(text, huffmanCodes)); System.out.println("Decoded text: " + decode(encode(text, huffmanCodes), root)); } private static Map<Character, Integer> buildFrequencyMap(String text) { Map<Character, Integer> frequencyMap = new HashMap<>(); for (char c : text.toCharArray()) { frequencyMap.put(c, frequencyMap.getOrDefault(c, 0) + 1); } return frequencyMap; } private static HuffmanNode buildHuffmanTree(Map<Character, Integer> frequencyMap) { PriorityQueue<HuffmanNode> priorityQueue = new PriorityQueue<>(); for (Map.Entry<Character, Integer> entry : frequencyMap.entrySet()) { priorityQueue.offer(new HuffmanNode(entry.getValue(), entry.getKey())); } while (priorityQueue.size() > 1) { HuffmanNode left = priorityQueue.poll(); HuffmanNode right = priorityQueue.poll(); HuffmanNode parent = new HuffmanNode(left.frequency + right.frequency, '-'); parent.left = left; parent.right = right; priorityQueue.offer(parent); } return priorityQueue.poll(); } private static Map<Character, String> buildHuffmanCodes(HuffmanNode root) { Map<Character, String> huffmanCodes = new HashMap<>(); buildHuffmanCodesHelper(root, "", huffmanCodes); return huffmanCodes; } private static void buildHuffmanCodesHelper(HuffmanNode node, String code, Map<Character, String> huffmanCodes) { if (node.isLeaf()) { huffmanCodes.put(node.data, code); return; } buildHuffmanCodesHelper(node.left, code + "0", huffmanCodes); buildHuffmanCodesHelper(node.right, code + "1", huffmanCodes); } private static String encode(String text, Map<Character, String> huffmanCodes) { StringBuilder encodedText = new StringBuilder(); for (char c : text.toCharArray()) { encodedText.append(huffmanCodes.get(c)); } return encodedText.toString(); } private static String decode(String encodedText, HuffmanNode root) { StringBuilder decodedText = new StringBuilder(); HuffmanNode current = root; for (char c : encodedText.toCharArray()) { 后面代码请补充完整
时间: 2024-02-14 10:25:00 浏览: 113
接下来的代码是对编码文本进行解码的部分,请继续阅读:
```java
for (char c : encodedText.toCharArray()) {
if (c == '0') {
current = current.left;
} else if (c == '1') {
current = current.right;
}
if (current.isLeaf()) {
decodedText.append(current.data);
current = root;
}
}
return decodedText.toString();
```
这段代码使用了当前字符的编码(0或1)来遍历Huffman树。如果遇到叶子节点,就将对应的字符添加到解码文本中,并将当前节点重新设置为根节点,以便继续解码下一个字符。最后返回解码后的文本。
希望这段代码能帮助到您!如果您有任何其他问题,请随时问我。
相关问题
在一个class里用java编写代码
为了实现本周实验的内容,可以使用Java编程语言来构建一个`BinaryTree`类以及一个`HuffmanTree`类。以下是具体的实现方案:
### 基本题 - 二叉树操作
#### BinaryTree 类定义
首先定义一个表示二叉树节点的内部类 `Node` 和主类 `BinaryTree`:
```java
public class BinaryTree {
static class Node {
int data;
Node left, right;
public Node(int item) {
data = item;
left = right = null;
}
}
Node root;
// 构造函数
public BinaryTree() {
this.root = null;
}
// 查找最大值的方法
public int findMax(Node node) {
if (node == null) return Integer.MIN_VALUE;
int res = node.data;
int lres = findMax(node.left);
int rres = findMax(node.right);
if (lres > res) res = lres;
if (rres > res) res = rres;
return res;
}
// 求所有节点数据总和的方法
public int sumOfNodes(Node node) {
if (node == null) return 0;
return node.data + sumOfNodes(node.left) + sumOfNodes(node.right);
}
// 获取树高度的方法
public int getHeight(Node node) {
if (node == null) return 0;
return Math.max(getHeight(node.left), getHeight(node.right)) + 1;
}
// 统计单分支节点数量的方法
public int countSingleChildNodes(Node node) {
if (node == null) return 0;
if ((node.left != null && node.right == null) || (node.left == null && node.right != null))
return 1 + countSingleChildNodes(node.left) + countSingleChildNodes(node.right);
else
return countSingleChildNodes(node.left) + countSingleChildNodes(node.right);
}
}
```
### 拓展题 - 哈夫曼树
#### HuffmanTree 类定义
接下来是创建哈夫曼树并生成编码的过程:
```java
import java.util.*;
public class HuffmanTree {
static class TreeNode implements Comparable<TreeNode> {
char ch;
int freq;
TreeNode left, right;
public TreeNode(char ch, int freq, TreeNode left, TreeNode right) {
this.ch = ch;
this.freq = freq;
this.left = left;
this.right = right;
}
@Override
public int compareTo(TreeNode other) {
return this.freq - other.freq;
}
}
private Map<Character, String> huffmanCodes = new HashMap<>();
public void buildHuffmanTree(String input) {
Map<Character, Integer> frequencyMap = getFrequency(input);
PriorityQueue<TreeNode> priorityQueue = new PriorityQueue<>();
for (char c : frequencyMap.keySet()) {
priorityQueue.add(new TreeNode(c, frequencyMap.get(c), null, null));
}
while (priorityQueue.size() > 1) {
TreeNode first = priorityQueue.poll();
TreeNode second = priorityQueue.poll();
TreeNode merged = new TreeNode('\0', first.freq + second.freq, first, second);
priorityQueue.add(merged);
}
TreeNode root = priorityQueue.poll();
generateCodes(root, "");
}
private Map<Character, Integer> getFrequency(String s) {
Map<Character, Integer> map = new HashMap<>();
for (char c : s.toCharArray()) {
map.put(c, map.getOrDefault(c, 0) + 1);
}
return map;
}
private void generateCodes(TreeNode node, String code) {
if (node == null) return;
if (node.ch != '\0') {
huffmanCodes.put(node.ch, code);
}
generateCodes(node.left, code + "0");
generateCodes(node.right, code + "1");
}
public String encode(String text) {
StringBuilder sb = new StringBuilder();
for (char c : text.toCharArray()) {
sb.append(huffmanCodes.get(c));
}
return sb.toString();
}
public String decode(String encodedText) {
StringBuilder sb = new StringBuilder();
TreeNode current = root;
for (char bit : encodedText.toCharArray()) {
if (bit == '0') {
current = current.left;
} else if (bit == '1') {
current = current.right;
}
if (current != null && current.ch != '\0') {
sb.append(current.ch);
current = root; // 重置到根节点
}
}
return sb.toString();
}
}
```
以上就是完整的Java实现,包括了二叉树的基本操作(查找最大值、求和、计算高度及统计单分支节点)和哈夫曼树的构建与编码解码功能。希望这对你有帮助!如果有任何疑问或需要进一步解释,请随时告诉我。
哈夫曼树java实现
哈夫曼树是一种用于数据压缩的树形结构,它通过将出现频率较高的字符用较短的编码表示,从而实现数据的高效压缩。下面是哈夫曼树的Java实现:
```java
import java.util.PriorityQueue;
class Node implements Comparable<Node> {
char data;
int frequency;
Node left, right;
public Node(char data, int frequency) {
this.data = data;
this.frequency = frequency;
left = right = null;
}
@Override
public int compareTo(Node node) {
return this.frequency - node.frequency;
}
}
public class HuffmanTree {
public static void main(String[] args) {
String text = "Hello, World!";
Node root = buildHuffmanTree(text);
String encodedText = encode(root, text);
String decodedText = decode(root, encodedText);
System.out.println("Original text: " + text);
System.out.println("Encoded text: " + encodedText);
System.out.println("Decoded text: " + decodedText);
}
public static Node buildHuffmanTree(String text) {
int[] frequencies = new int[256];
for (char c : text.toCharArray()) {
frequencies[c]++;
}
PriorityQueue<Node> queue = new PriorityQueue<>();
for (int i = 0; i < 256; i++) {
if (frequencies[i] > 0) {
queue.add(new Node((char) i, frequencies[i]));
}
}
while (queue.size() > 1) {
Node left = queue.poll();
Node right = queue.poll();
Node parent = new Node('\0', left.frequency + right.frequency);
parent.left = left;
parent.right = right;
queue.add(parent);
}
return queue.poll();
}
public static String encode(Node root, String text) {
StringBuilder encodedText = new StringBuilder();
encodeHelper(root, text, encodedText);
return encodedText.toString();
}
private static void encodeHelper(Node node, String text, StringBuilder encodedText) {
if (node == null) {
return;
}
if (node.left == null && node.right == null) {
encodedText.append(node.data);
return;
}
encodeHelper(node.left, text, encodedText);
encodeHelper(node.right, text, encodedText);
}
public static String decode(Node root, String encodedText) {
StringBuilder decodedText = new StringBuilder();
Node current = root;
for (char c : encodedText.toCharArray()) {
if (c == '0') {
current = current.left;
} else if (c == '1') {
current = current.right;
}
if (current.left == null && current.right == null) {
decodedText.append(current.data);
current = root;
}
}
return decodedText.toString();
}
}
```
以上是一个简单的哈夫曼树的Java实现。它包括了构建哈夫曼树、编码和解码的功能。你可以通过调用`buildHuffmanTree`方法来构建哈夫曼树,然后使用`encode`方法对文本进行编码,使用`decode`方法对编码后的文本进行解码。
阅读全文