哈夫曼树操作

树节点

public class TreeNode {
    private T data;
    private TreeNode left;
    private TreeNode right;

    public T getData() {
        return data;
    }

    public void setData(T data) {
        this.data = data;
    }

    public TreeNode getLeft() {
        return left;
    }

    public void setLeft(TreeNode left) {
        this.left = left;
    }

    public TreeNode getRight() {
        return right;
    }

    public void setRight(TreeNode right) {
        this.right = right;
    }
}

创建哈夫曼树(最优二叉树)

public static TreeNode createHuffmanTree(int[] arr) {

    ArrayList> list = new ArrayList<>();

    for (int value : arr) {
        TreeNode node = new TreeNode<>();
        node.setData(value);
        list.add(node);
    }

    while (list.size() > 1) {
        /**
         * 将所有节点按照节点的权升序排序
         */
        Collections.sort(list, Comparator.comparingInt(TreeNode::getData));

        TreeNode left = list.get(0);
        TreeNode right = list.get(1);
        TreeNode node = new TreeNode<>();
        node.setData(left.getData() + right.getData());
        node.setLeft(left);
        node.setRight(right);

        list.remove(left);
        list.remove(right);
        list.add(node);
    }
    return list.get(0);
}

你可能感兴趣的:(哈夫曼树操作)