import java.util.ArrayList;
import java.util.Collections;
public class HafuManTree {
public static void main(String[] args) {
int[] arr = {2, 4, 7, 3, 4, 0, 6};
Node node = creatTree(arr);
node.preList(node);
}
//构建哈夫曼数
public static Node creatTree(int[] arr) {
ArrayList<Node> nodes = new ArrayList<>();
//将数组封装成一个个节点放入集合
for (int value : arr) {
nodes.add(new Node(value));
}
while (nodes.size() > 1) {
//排序
Collections.sort(nodes);
//每次将前两个数构成子树
Node leftnode = nodes.get(0);
Node rightnode = nodes.get(1);
//将新创建的数放入集合
Node parent = new Node(leftnode.getValue() + rightnode.getValue());
//将左右子树挂在父节点上
parent.setLeft(leftnode);
parent.setRight(rightnode);
//将父节点添加进集合
nodes.add(parent);
//删除原来的数
nodes.remove(leftnode);
nodes.remove(rightnode);
}
return nodes.get(0);
}
}
//创建节点
class Node implements Comparable<Node> {
private int value;
private Node left;
private Node right;
//前序遍历
public void preList(Node root){
System.out.println(root);
//遍历左节点
if (root.left != null){
preList(root.left);
}
//遍历右节点
if (root.right != null){
preList(root.right);
}
}
public Node() {
}
public Node(int value) {
this.value = value;
}
@Override
public int compareTo(Node o) {
return this.value - o.value;
}
/**
* 获取
*
* @return value
*/
public int getValue() {
return value;
}
/**
* 设置
*
* @param value
*/
public void setValue(int value) {
this.value = value;
}
/**
* 获取
*
* @return left
*/
public Node getLeft() {
return left;
}
/**
* 设置
*
* @param left
*/
public void setLeft(Node left) {
this.left = left;
}
/**
* 获取
*
* @return right
*/
public Node getRight() {
return right;
}
/**
* 设置
*
* @param right
*/
public void setRight(Node right) {
this.right = right;
}
public String toString() {
return "Node: value = " + value;
}
}
Java数据结构---哈夫曼树问题
最新推荐文章于 2024-09-23 14:50:51 发布