Java实现哈夫曼树的构建

public class test {
    //构建有序链表,从小到大排序
    public static node insert(node root, node s){
        node p1,p2;
        if(root == null){
            root = s;
        }else {
            p1 = null;
            p2 = root;
            while(p2!= null && p2.data < s.data){
                p1 = p2;;
                p2 = p2.next;
            }
            s.next = p2;
            if(p1 == null){
                root = s;
            }else{
                p1.next = s;
            }
        }
        return root;
    }
    //构建huffman树
    public static node creathuffman(node root){
        node s,rl,rr;
        //每次从中找出两个最小节点
        while(root != null && root.next != null){
            rl = root;
            rr = root.next;
            root = rr.next;
            s= new node(rl.data+rr.data);
            s.next = null;
            s.data = rl.data + rr.data;
            s.left = rl;
            s.right = rr;
            rl.parent = s;
            rr.parent = s;
            rl.next = rr.next = null;
            root = insert(root,s);
        }
        return root;
    }
    //前序遍历二叉树
    public static void preorder(node t){
        if(t != null){
            System.out.println(t.data);
            preorder(t.left);
            preorder(t.right);
        }
    }
    //中序遍历二叉树
    public static void inorder(node t){
        if(t != null){
            inorder(t.left);
            System.out.println(t.data);
            inorder(t.right);
        }
    }

    public static void main(String[] args) {
        node root = null;
        node s;
        int[] array = {7,5,2,4};
        for(int i = 0; i < array.length; i ++){
            s = new node(array[i]);
            s.next = null;
            s.left = s.right = null;
            root = insert(root,s);
        }
        root = creathuffman(root);
        System.out.println("前序排列为:");
        preorder(root);
        System.out.println("中序排列为:");
        inorder(root);
    }
}
public class node {
    int data;
    node left;
    node right;
    node next;
    node parent;

    public node(int data){
        this.data = data;
        this.left = null;
        this.right = null;
        this.next = null;
        this.parent = null;
    }
}

猜你喜欢

转载自blog.csdn.net/weixin_43408956/article/details/89422225