private int value;
private Node1 leftChild;
private Node1 rightChild;
public Node1(int value) {
this.value = value;
}
public int getValue() {
return value;
}
public void setValue(int value) {
this.value = value;
}
public Node1 getLeftChild() {
return leftChild;
}
public void setLeftChild(Node1 left) {
this.leftChild = left;
}
public Node1 getRightChild() {
return rightChild;
}
public void setRightChild(Node1 rightChild) {
this.rightChild = rightChild;
}
public int compareTo(Object o) {
Node1 that = (Node1) o;
double result = this.value - that.value;
return result > 0 ? 1 : result == 0 ? 0 : -1;
}
}
/**
*
* 哈夫曼树构造类:
*/
class HuffmanTreeBuilder {
public static void ss() {
List<Node1> nodes = Arrays.asList(
new Node1(1),
new Node1(3),
new Node1(5),
new Node1(7)
);
Node1 node = HuffmanTreeBuilder.build(nodes);
PrintTree(node);
}
/**
*
* 构造哈夫曼树
*
* @param nodes
* 结点集合
*
* @return 构造出来的树的根结点
*/
private static Node1 build(List<Node1> nodes) {
nodes = new ArrayList<Node1>(nodes);
sortList(nodes);
while (nodes.size() > 1) {
createAndReplace(nodes);
}
return nodes.get(0);
}
/**
*
* 组合两个权值最小结点,并在结点列表中用它们的父结点替换它们
*
* @param nodes
* 结点集合
*/
private static void createAndReplace(List<Node1> nodes) {
Node1 left = nodes.get(0);
Node1 right = nodes.get(1);
Node1 parent = new Node1(left.getValue() + right.getValue());
parent.setLeftChild(left);
parent.setRightChild(right);
nodes.remove(0);
nodes.remove(0);
nodes.add(parent);
sortList(nodes);
}
/**
*
* 将结点集合由大到小排序
*/
private static void sortList(List<Node1> nodes) {
Collections.sort(nodes);
}
/**
*
* 打印树结构,显示的格式是node(left,right)
*
* @param node
*/
public static void PrintTree(Node1 node)
{
Node1 left = null;
Node1 right = null;
if (node != null)
{
System.out.print(node.getValue());
left = node.getLeftChild();
right = node.getRightChild();
System.out.println("(" + (left != null ? left.getValue() : " ")
+ "," + (right != null ? right.getValue() : " ") + ")");
}
if (left != null)
PrintTree(left);
if (right != null)
PrintTree(right);
}
}