[Java]赫夫曼树

赫夫曼树又称最优二叉树:每个叶子节点带权值为wi,则树的带权路径长度最小的二叉树称为最优二叉树。

package tree;


public class HuffmanTree {
    public static int[] min (Note[] note,int n) {

        int min1 = Integer.MAX_VALUE - 1;
        int j = -1;
        int min2 = Integer.MAX_VALUE;
        int k = -1;
        for (int i = 0;i < n; i ++) {
            if (note[i].parent == -1 && note[i].weight < min1) {
                min1 = note[i].weight;
                j = i;
            } else if (note[i].parent == -1 && note[i].weight < min2) {
                min2 = note[i].weight;
                k = i;
            }
        }
        return new int[]{j,k};
    }
    public static void merge (Note[] note, int i, int j, int n) {
        note[i].parent = note[j].parent = n;
        note[n] = new Note(note[i].weight + note[j].weight,i,j,-1);
    }
    public static void mid (Note[] note, int t) {  //中序遍历
        if (t == -1) return;
        System.out.print(note[t].weight + ",");
        mid(note,note[t].lChild);
        mid(note,note[t].rChild);
    }
    public static void main(String[] args) {
        int n = 5;       //叶子节点的数量
        int[] weight = new int[]{5,15,40,30,10};   //叶子结点的权值
        Note[] note = new Note[2 * n - 1];           //采用顺序存储结构
        for (int i = 0;i < n;i ++) {               //建立每一个叶子节点对象,并把每一个叶子节点看作一棵树
            note[i] = new Note(weight[i],-1,-1,-1);
        }
        for (int i = n; i < 2 * n - 1; i ++) {
            int[] min = min(note, i);      //选出权值最小的两个跟节点
            merge(note,min[0],min[1],i);  //合并两个权值最小的树
        }
        mid(note,2 * n - 2);
    }
}
class Note {
    int weight;
    int lChild, rChild;
    int parent;
    public Note(int weight, int lChild, int rChild, int parent) {
        this.weight = weight;
        this.lChild = lChild;
        this.rChild = rChild;
        this.parent = parent;
    }
}

发布了57 篇原创文章 · 获赞 55 · 访问量 1939

猜你喜欢

转载自blog.csdn.net/qq_40561126/article/details/104554946