[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;
    }
}

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章