Java数据结构---哈夫曼树问题

import java.util.ArrayList;
import java.util.Collections;

public class HafuManTree {
    public static void main(String[] args) {
        int[] arr = {2, 4, 7, 3, 4, 0, 6};
        Node node = creatTree(arr);
        node.preList(node);
    }

    //构建哈夫曼数
    public static Node creatTree(int[] arr) {
        ArrayList<Node> nodes = new ArrayList<>();
        //将数组封装成一个个节点放入集合
        for (int value : arr) {
            nodes.add(new Node(value));
        }
        while (nodes.size() > 1) {
            //排序
            Collections.sort(nodes);
            //每次将前两个数构成子树
            Node leftnode = nodes.get(0);
            Node rightnode = nodes.get(1);
            //将新创建的数放入集合
            Node parent = new Node(leftnode.getValue() + rightnode.getValue());
            //将左右子树挂在父节点上
            parent.setLeft(leftnode);
            parent.setRight(rightnode);
            //将父节点添加进集合
            nodes.add(parent);
            //删除原来的数
            nodes.remove(leftnode);
            nodes.remove(rightnode);
        }
        return nodes.get(0);
    }
}

//创建节点
class Node implements Comparable<Node> {
    private int value;
    private Node left;
    private Node right;

    //前序遍历
    public void preList(Node root){
        System.out.println(root);
        //遍历左节点
        if (root.left != null){
            preList(root.left);
        }
        //遍历右节点
        if (root.right != null){
            preList(root.right);
        }
    }
    public Node() {
    }

    public Node(int value) {
        this.value = value;
    }

    @Override
    public int compareTo(Node o) {
        return this.value - o.value;
    }


    /**
     * 获取
     *
     * @return value
     */
    public int getValue() {
        return value;
    }

    /**
     * 设置
     *
     * @param value
     */
    public void setValue(int value) {
        this.value = value;
    }

    /**
     * 获取
     *
     * @return left
     */
    public Node getLeft() {
        return left;
    }

    /**
     * 设置
     *
     * @param left
     */
    public void setLeft(Node left) {
        this.left = left;
    }

    /**
     * 获取
     *
     * @return right
     */
    public Node getRight() {
        return right;
    }

    /**
     * 设置
     *
     * @param right
     */
    public void setRight(Node right) {
        this.right = right;
    }

    public String toString() {
        return "Node: value = " + value;
    }
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值