package DataStructure;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.List;
/**
* Created with IntelliJ IDEA.
* Description:
* User: 86178
* Date: 2024-03-05
* Time: 17:34
*/
public class HuffmanTree {
public static void main(String[] args) {
int[] arr = {13, 7, 8, 3, 29, 6, 1};
Node root=createHuffmanTree(arr);
preOrder(root);
}
//前序遍历
public static void preOrder(Node root){
if(root==null){
System.out.println("节点为空");
}else{
root.preOrder();
}
}
//创建赫夫曼树
public static Node createHuffmanTree(int[] arr) {
List<Node> nodes = new ArrayList<Node>();
for (int val : arr) {
Node newNode = new Node(val);
nodes.add(newNode);
}
//进行排序
while (nodes.size() > 1) {
Collections.sort(nodes);
//1 取出权值最小的二叉树
Node left = nodes.get(0);
Node right = nodes.get(1);
Node parent = new Node(left.val + right.val);
parent.left = left;
parent.right = right;
//删除left right
nodes.remove(left);
nodes.remove(right);
//加入parent
nodes.add(parent);
//再次进行排序
}
//Collections.sort(nodes);
//System.out.println("nodes=" + nodes);
return nodes.get(0);
}
}
//创建节点类
class Node implements Comparable<Node> {
public int val;
public Node left;
public Node right;
public Node(int val) {
this.val = val;
}
public void preOrder() {
System.out.print(this.val+" ");
if (this.left != null) this.left.preOrder();
if (this.right != null) this.right.preOrder();
}
@Override
public String toString() {
return "Node [val=" + val + "]";
}
@Override
public int compareTo(Node o) {
return this.val - o.val;//对权值进行比较
}
}
尚硅谷Java数据结构--赫夫曼树
本文介绍了如何使用Java编程实现Huffman树的创建过程,包括构建节点类、利用数组输入创建节点、通过比较权值合并最小的二叉树节点,最后返回根节点并演示了前序遍历方法。
摘要由CSDN通过智能技术生成